2012-05-16 63 views
14

Tôi đang tạo ứng dụng bằng Netbeans 7.1.2 và tôi đang sử dụng trình chọn tệp nhưng tôi không muốn trình chọn tệp nhận tệp, thay vào đó tôi muốn nó trở lại đường dẫn đầy đủ đến thư mục hiện đang ở.Cách lấy thư mục đường dẫn đầy đủ từ Trình chọn tệp

What the file chooser looks like

Khi người dùng nhấp mở ở đây, tôi muốn nó để trả lại đường dẫn đầy đủ và không phải là tập tin. Làm thế nào để tôi làm điều này?

Trả lời

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

Từ http://www.java2s.com/Code/Java/Swing-JFC/SelectadirectorywithaJFileChooser.htm

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

Nếu bạn muốn biết thư mục hiện hành:

fileChooser.getCurrentDirectory() 

Nếu bạn muốn để có được các tập tin được lựa chọn:

fileChooser.getSelectedFile(); 

Để có được đường dẫn tuyệt đối tới một tệp:

file.getAbsolutePath(); 

Lấy tất cả các thông tin trên the File chooser API here.

0

Đặt trình chọn tệp của bạn để lọc ra tất cả các tệp không phải thư mục.

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

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

Trong netbeans, màn hình hiển thị mã tự động (phương pháp hiển thị) cơ sở sẽ cung cấp danh sách đầy đủ các phương pháp có sẵn để JFileChooser một khi bạn đã sử dụng toán tử dấu chấm bên cạnh JFileChooser dụ. Chỉ cần điều hướng qua các phương thức getter để tìm hiểu thêm các tùy chọn và đọc Javadock nhỏ được hiển thị bởi netbeans.

0

On JDK 1.8 (sử dụng NetBeans 8.0.1) hoạt động này:

String path = jOpen.getName(diagOpen.getSelectedFile()); // file's name only 

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

jOpen là JFileChooser. Như được chỉ ra bởi Joachim, File class doesn't leave anything opened nor leaked

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