JFileChooser - open in current directory
Asked Answered
C

1

22

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!

Clotilda answered 3/2, 2014 at 18:11 Comment(1)
java.io.File.getCanonicalPath()?Haggar
M
39

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

File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);
Milore answered 3/2, 2014 at 18:24 Comment(2)
This returns the users home directory, but not the wanted Netbeans project directory.Mouser
@CoSoCo, it returns the working directory, which is what the original question was asking for as a substitute for using "." in the provided code. The working directory may or may not be the Netbeans directory, depending on how Java was started.Milore

© 2022 - 2024 — McMap. All rights reserved.