2011-12-09 63 views
5

Làm thế nào tôi có thể nhận được đường dẫn tuyệt đối của một thư mục bằng cách sử dụng JFileChooser, chỉ cần chọn thư mục?Lấy đường dẫn của một thư mục bằng cách sử dụng JFileChooser

+1

Xem tài liệu. Lấy java.io.File: [ở đây] (http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html#getSelectedFile%28%29). Chỉ chọn các thư mục: [tại đây] (http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html#setFileSelectionMode%28int%29). –

Trả lời

12

Sử dụng:

chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
//or 
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); 

cùng với:

chooser.getCurrentDirectory() 
//or 
chooser.getSelectedFile(); 

sau đó gọi getAbsoluteFile() trên đối tượng File trả lại.

6

JFileChooser Phương thức getSelectedFile(), trả về đối tượng File. Sử dụng getAbsolutePath() để lấy tên tuyệt đối cho tệp.

sửa đổi ví dụ từ 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()); 
} 
2

Hãy thử:

chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 

File file = chooser.getSelectedFile(); 
String fullPath = file.getAbsolutePath(); 

System.out.println(fullPath); 

fullpath mang đến cho bạn con đường tuyệt đối cần thiết của thư mục được chọn

Các vấn đề liên quan