Harsha
Harsha

Reputation: 3578

Get the path of a directory using JFileChooser

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

Upvotes: 9

Views: 37827

Answers (3)

c00kiemon5ter
c00kiemon5ter

Reputation: 17594

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());
}

Upvotes: 8

sonu thomas
sonu thomas

Reputation: 2161

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

Upvotes: 3

Wojciech Owczarczyk
Wojciech Owczarczyk

Reputation: 5735

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.

Upvotes: 16

Related Questions