JFileChooser - open in current directory

CodeGuy picture CodeGuy · Feb 3, 2014 · Viewed 27.6k times · Source

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!

Answer

Nathaniel Jones picture Nathaniel Jones · Feb 3, 2014

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

File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);