JFileChooser getCurrentDirectory returning wrong current directory?
Asked Answered
A

3

11

I am using JFileChooser in an app to browse for a directory however when I select the directory it returns the path to the folder above the folder I selected. i.e. I select "C:\Test" and it returns "C:\"

Here is the Code I'm Using

            JFileChooser c = new JFileChooser();
            c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int rVal = c.showSaveDialog(c);
            if (rVal == JFileChooser.APPROVE_OPTION) {
                txtDirectory.setText("");
                CC_Test.MsgBox(c.getCurrentDirectory().toString());
                txtDirectory.setText(c.getCurrentDirectory().toString());
            }
            if (rVal == JFileChooser.CANCEL_OPTION) {
                txtDirectory.setText("");
            }
Adonis answered 6/1, 2012 at 19:45 Comment(0)
D
17

You should use

c.getSelectedFile()

instead of

c.getCurrentDirectory()

in order to get the selected file (aka directory in this case). Otherwise it yields the directory which is shown in the filechooser's panel (which is the parent) and not the one which is selected.

Daloris answered 6/1, 2012 at 19:55 Comment(1)
The truth is super ambiguous, but this is it.Cayser
P
3

For getting the selected file or directory, use:

c.getSelectedFile();

If you use

c.getCurrentDirectory();

the return depends on the operating system.

Philae answered 6/1, 2012 at 19:54 Comment(0)
M
3

You have to use JFileChooser.getSelectedFile(). The File class is both for directories and files.

Mangum answered 6/1, 2012 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.