簡體   English   中英

如何從File Chooser獲取完整路徑目錄

[英]How to get full path directory from File Chooser

我正在使用Netbeans 7.1.2創建一個應用程序,我正在使用文件選擇器,但我不希望文件選擇器獲取文件,而是我希望它返回它當前所在目錄的完整路徑。

文件選擇器的樣子

當用戶在此處單擊打開時,我希望它返回完整路徑而不是文件。 我該怎么做呢?

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

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

如果你想知道當前目錄:

fileChooser.getCurrentDirectory()

如果要獲取所選文件:

fileChooser.getSelectedFile();

獲取文件的絕對路徑:

file.getAbsolutePath();

此處獲取File chooser API所有信息。

設置文件選擇器以過濾掉所有非目錄文件。

yourFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File f = fileChooser.getCurrentDirectory(); //This will return the directory

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

在netbeans中,一旦您使用了JFileChooser實例旁邊的點運算符,自動代碼顯示(方法顯示)工具將提供JFileChooser可用的完整方法列表。 只需瀏覽getter方法以找到更多選項,並閱讀netbeans顯示的小Javadock。

在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類不會留下任何打開或泄露的東西

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM