[英]Importing files from local file system in Java
Java是否允許您在不指定實際文件的情況下將文件從本地目錄導入到程序中? 我希望用戶選擇自己的文本文件導入我的程序。 我只搜索了有關如何使用已知的.txt文件讀取文件的示例。
您可以通過多種方式允許用戶選擇文件,而無需將文件名實際硬編碼到程序中。
這是一個使用JFileChooser的Swing類的示例
import javax.swing.JFileChooser;
import java.io.File;
public class ChooseFile
{
public static void main(String[] args)
{
// Create JFileChooser
JFileChooser fileChooser = new JFileChooser();
// Set the directory where the JFileChooser will open to
// Uncomment one of these below as an example
// fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
// fileChooser.setCurrentDirectory(new File("c:\\"));
// Show the file select box to the user
int result = fileChooser.showOpenDialog(null);
// Did the user select the "Open" button
if(result == JFileChooser.APPROVE_OPTION)
System.out.println("File chosen: " + fileChooser.getSelectedFile());
else
System.out.println("No file chosen");
}
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.