How to get full path directory from File Chooser
Asked Answered
D

6

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?

Debi answered 16/5, 2012 at 15:24 Comment(0)
F
21
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

Ferrocyanide answered 16/5, 2012 at 15:27 Comment(0)
D
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.

Decoder answered 16/5, 2012 at 15:28 Comment(0)
S
2
File file = fileChooser.getCurrentDirectory();
String fullPath = file.getCanonicalPath(); // or getAbsolutePath()
Secundas answered 16/5, 2012 at 15:27 Comment(0)
W
0

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

yourFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
Watthour answered 16/5, 2012 at 15:30 Comment(0)
P
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.

Pagas answered 16/5, 2012 at 15:46 Comment(0)
H
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

Hamhung answered 28/11, 2014 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.