JFileChooser getCurrentDirectory returns invalid current directory?

I use JFileChooser in the application to search for a directory, but when I select a directory, it returns the path to the folder above the folder I selected. that is, I select "C: \ Test" and return "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(""); } 
+7
source share
3 answers

You have to use

 c.getSelectedFile() 

instead

 c.getCurrentDirectory() 

to get the selected file (in this case, the directory). Otherwise, it issues a directory that appears in the filechooser panel (which is the parent), and not the one that is selected.

+12
source

To get the selected file or directory, use:

 c.getSelectedFile(); 

If you use

 c.getCurrentDirectory(); 

The return depends on the operating system.

+3
source

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

+3
source

All Articles