9

How can I get the absolute path of a directory using JFileChooser, just selecting the directory?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Harsha
  • 3,548
  • 20
  • 52
  • 75
  • 1
    See the documentation. Getting the java.io.File: [here](http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html#getSelectedFile%28%29). Selecting only directories: [here](http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html#setFileSelectionMode%28int%29). – S.L. Barth is on codidact.com Dec 09 '11 at 11:05

3 Answers3

16

Use:

chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//or
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

together with:

chooser.getCurrentDirectory()
//or
chooser.getSelectedFile();

then call getAbsoluteFile() on the File object returned.

Wojciech Owczarczyk
  • 5,595
  • 2
  • 33
  • 55
8

JFileChooser's getSelectedFile() method, returns a File object. Use the getAbsolutePath() to get the absolute name to the file.

modified example from the javadoc:

JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this directory: " +
        chooser.getSelectedFile().getAbsolutePath());
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
3

Try:

chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

File file = chooser.getSelectedFile();
String fullPath = file.getAbsolutePath();

System.out.println(fullPath);

fullPath gives you the required Absolute path of the Selected directory

sonu thomas
  • 2,161
  • 4
  • 24
  • 38