Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFileChooser - open in current directory

Tags:

I have a simple JFileChooser set up in the following manner

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(new FileFilter() {
     ...
});

int v = chooser.showOpenDialog(this);
if (v == JFileChooser.APPROVE_OPTION) {
     File file = chooser.getSelectedFile();
     System.out.println(file.getAbsolutePath());
}

As you can see, this FileChooser starts out in the current directory, which in my Netbeans project, is the root of the project folder. Here's the problem: When I select a file and it prints out the absolute path, it includes the "." in the path. For instance, the output I get is:

/Users/MyName/Folder1/Folder2/./Temp.xls

Of course, this is weird, especially since I'm displaying this to the user. Now, I could be hacky and do some fun post substring processing stuff to get rid of that "/./" portion. But...is there a non-lazy programmer way to fix this problem? Thanks in advance!

like image 321
CodeGuy Avatar asked Feb 03 '14 18:02

CodeGuy


1 Answers

Use the system property "user.dir" as follows:

File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);
like image 153
Nathaniel Jones Avatar answered Oct 07 '22 21:10

Nathaniel Jones