2012-05-16 50 views
14

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

What the file chooser looks like

當用戶點擊這裏打開,我希望它返回的完整路徑,而不是文件。我該怎麼做呢?

回答

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

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

如果你想知道當前目錄:

fileChooser.getCurrentDirectory() 

如果你想選擇的文件:

fileChooser.getSelectedFile(); 

要獲得文件的絕對路徑:

file.getAbsolutePath(); 

抓住了the File chooser API here的所有信息。

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方法的完整列表,一旦你使用了旁邊的JFileChooser實例點操作。只需瀏覽getter方法即可找到更多選項,並閱讀由netbeans顯示的小型Javadock。

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中。正如約阿希姆所指出的,File class doesn't leave anything opened nor leaked

相關問題