繁体   English   中英

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

[英]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.

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