Currently I have
final JFileChooser fc = new JFileChooser("src\\MovieBoxOffice\\MovieFiles");
int returnVal = fc.showOpenDialog(openJButton);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
File selectedFile = fc.getSelectedFile();
String filename = selectedFile.getAbsolutePath();
(....rest of code)
so filename is the FULL path. It looks something like
F:\Project3\src\MovieBoxOffice\MovieFiles\November2015.txt
I want it to end up getting just
November2015.txt
It'd be even better if it's just November2015
I can't seem to find a method that just straight up gets the file name.
I tried using the split method.
String[] str = filename.split("\\");
so I can get the last item of the array, which would be the file name. But that line of code is throwing exceptions:
Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
How can I get just the base filename?
selectedFile.getName()
. Seriously, don't convert it to a String
to begin with, File
has to many nice methods, like selectedFile.getParentFile()
will return you File
reference to the path of the file!
For example...
File selectedFile = new File("F:\\Project3\\src\\MovieBoxOffice\\MovieFiles\\November2015.txt");
System.out.println(selectedFile.getName());
System.out.println(selectedFile.getParentFile());
Which outputs...
November2015.txt
F:\Project3\src\MovieBoxOffice\MovieFiles
So, the answer is, ditch filename
, use selectedFile
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.