我需要在運行時期間爲我的java程序獲取文件路徑。有什麼方法可以使用默認的對話框來選擇一個單個文件並獲得完整路徑和名稱?如何在java中選擇文件?
它只是選擇一個文件,並得到其路徑爲String對象
能否請您爲它或教程提供的代碼?
PS:Windows操作系統
我需要在運行時期間爲我的java程序獲取文件路徑。有什麼方法可以使用默認的對話框來選擇一個單個文件並獲得完整路徑和名稱?如何在java中選擇文件?
它只是選擇一個文件,並得到其路徑爲String對象
能否請您爲它或教程提供的代碼?
PS:Windows操作系統
下面是從JFileChooser
文檔複製麪食發送到null
父的例子。
public class PickAFile {
public static void main(String[] args){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
}
}
如果你不喜歡的JFileChooser的外觀嘗試FileDialog
。
FileDialog dialog = new FileDialog((Frame)null, "Select File to Open");
dialog.setMode(FileDialog.LOAD);
dialog.setVisible(true);
String file = dialog.getFile();
System.out.println(file + " chosen.");
非常感謝。有效!! –
有沒有辦法得到完整的路徑?感謝後發現它。 chooser.getSelectedFile()。getAbsolutePath()); – Mike
它是一個GUI程序,你正在尋找?你想要構建什麼應用程序? –
如果您正在使用swing [JFileChooser](https://docs.oracle.com/javase/8/docs/api/javax/swing/JFileChooser.html)或[FileDialog](https://docs.oracle.com /javase/8/docs/api/java/awt/FileDialog.html)如果您使用的是javafx,[FileChooser](https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser的.html)。 JFileChooser文檔有一個使用示例。 – matt
@ shreyas-sarvothama是的我正在尋找GUI文件選擇器 –