简体   繁体   English

使用Java从本地文件系统导入文件

[英]Importing files from local file system in Java

Does Java allow you to import files from a local directory into a program without specifying an actual file? Java是否允许您在不指定实际文件的情况下将文件从本地目录导入到程序中? I want the user to choose their own text file to import into my program. 我希望用户选择自己的文本文件导入我的程序。 I've searched only to find examples on how to read in files with the .txt file already known. 我只搜索了有关如何使用已知的.txt文件读取文件的示例。

There are multiple ways in which you can allow a user to select a file without actually hard-coding the filename into the program. 您可以通过多种方式允许用户选择文件,而无需将文件名实际硬编码到程序中。

Here is one example using the Swing class of JFileChooser 这是一个使用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");          
    } 
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM