Get the path of a directory using JFileChooser
Asked Answered
G

3

9

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

Guacin answered 9/12, 2011 at 11:0 Comment(1)
See the documentation. Getting the java.io.File: here. Selecting only directories: here.Cristal
T
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.

Tarrel answered 9/12, 2011 at 11:4 Comment(0)
D
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());
}
Danseuse answered 9/12, 2011 at 11:6 Comment(0)
B
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

Burlesque answered 9/12, 2011 at 11:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.