How to get full path directory from File Chooser

newSpringer picture newSpringer · May 16, 2012 · Viewed 50.2k times · Source

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?

Answer

Malcolm Smith picture Malcolm Smith · May 16, 2012
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