如何从文件选择器中获取完整路径目录

14

我正在使用Netbeans 7.1.2创建一个应用程序,并使用文件选择器,但是我不想让文件选择器获取文件,而是希望它返回当前所在目录的完整路径。

文件选择器的外观

当用户点击“打开”时,我希望它返回整个路径而不是文件。我该怎么做?

6个回答

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

来源于http://www.java2s.com/Code/Java/Swing-JFC/SelectadirectorywithaJFileChooser.htm


3

如果您想知道当前目录:

fileChooser.getCurrentDirectory()

如果您想获取所选文件:

fileChooser.getSelectedFile();

获取文件的绝对路径的方法如下:
file.getAbsolutePath();

在这里获取有关文件选择器API的所有信息


2
File file = fileChooser.getCurrentDirectory();
String fullPath = file.getCanonicalPath(); // or getAbsolutePath()

0
在JDK 1.8(使用NetBeans 8.0.1)上,这个可以工作:
String path = jOpen.getName(diagOpen.getSelectedFile()); // file's name only

String path = jOpen.getSelectedFile().getPath(); // full path

jOpen是jFileChooser。正如Joachim所指出的那样,File类不会留下任何打开或泄漏的内容


0

设置文件选择器以过滤掉所有非目录文件。

yourFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

0
File f = fileChooser.getCurrentDirectory(); //This will return the directory

File f = fileChooser.getSelectedFile(); //This will return the file

在NetBeans中,自动代码显示(方法显示)功能将提供完整的方法列表,一旦您在JFileChooser实例旁边使用了点运算符。只需浏览getter方法以查找更多选项,并阅读NetBeans显示的小Javadock即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接