14

I am creating an application using Netbeans 7.1.2 and I am using a file chooser, but i do not want the file chooser to get a file, instead i want it to return the full path to the directory that it is currently at.

What the file chooser looks like

When the user clicks open here, I want it to return the full path and not the file. How do I do this?

Community
  • 1
  • 1
newSpringer
  • 1,018
  • 10
  • 28
  • 44

6 Answers6

20
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
  System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
  System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
} else {
  System.out.println("No Selection ");
}

From http://www.java2s.com/Code/Java/Swing-JFC/SelectadirectorywithaJFileChooser.htm

Malcolm Smith
  • 3,540
  • 25
  • 29
3

If you want to know the current directory:

fileChooser.getCurrentDirectory()

If you want to get the selected file:

fileChooser.getSelectedFile();

To get the absolute path to a file:

file.getAbsolutePath();

Grab all the infos on the File chooser API here.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
2
File file = fileChooser.getCurrentDirectory();
String fullPath = file.getCanonicalPath(); // or getAbsolutePath()
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

Set your file chooser to filter out all non-directory files.

yourFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
FThompson
  • 28,352
  • 13
  • 60
  • 93
0
File f = fileChooser.getCurrentDirectory(); //This will return the directory

File f = fileChooser.getSelectedFile(); //This will return the file

In netbeans, the automatic code display(method display) facility will give the complete list of methods available to JFileChooser once you have used the dot operator next to JFileChooser instance. Just navigate through the getter methods to find out more options, and read the small Javadock displayed by netbeans.

PeakGen
  • 21,894
  • 86
  • 261
  • 463
0

On JDK 1.8 (using NetBeans 8.0.1) this works:

String path = jOpen.getName(diagOpen.getSelectedFile()); // file's name only

String path = jOpen.getSelectedFile().getPath(); // full path

jOpen is the jFileChooser. As pointed out by Joachim, File class doesn't leave anything opened nor leaked

Community
  • 1
  • 1
Broken_Window
  • 2,037
  • 3
  • 21
  • 47