繁体   English   中英

尝试读取文件时获取java.io.FileNotFoundException

[英]Getting java.io.FileNotFoundException when trying to read a file

我正在编写一个读取csv文件并将内容显示到JList中的小应用程序。

我当前的问题是, new FileReader(file)代码不断给我一个java.io.FileNotFoundException错误,我不太清楚为什么。

loadFile.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent actionEvent)
            {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("~/"));

                if (fileChooser.showOpenDialog(instance) == JFileChooser.APPROVE_OPTION)
                {
                    File file = fileChooser.getSelectedFile();
                    CSVReader reader = new CSVReader(new FileReader(file.getAbsolutePath()));
                    fileLocation.setText(file.getAbsolutePath());

                }
            }
        });
new File("~/")

~是主目录的Shell快捷方式。 使用像

new File("/home/myself/")

如@pickypg所指出的,如果传递的目录无效,则JFileChooser.setCurrentDirectory()会将用户的主目录设置为默认目录。 因此,即使File()不能像Shell那样解释~JFileChooser也会在用户的主目录中启动-但这适用于所有不存在的目录,例如

new File("/Windows")   // JFileChooser would start in "\Windows"
new File("/xWindows")   // JFileChooser would start in the user's home directory

如文档所述,用户的主目录是系统特定的,但在MS Windows上,通常是“我的文档”文件夹。

但是,即使使用了不存在的路径(例如~~), JFileChooser.getSelectedFile()也会返回正确的路径,因此FileReader()不应抛出FileNotFoundException


根据评论,事实证明问题不是运行时异常,而是未捕获到异常的编译时错误。 FileReader()构造函数周围添加一个try{}catch{}块:

try {
    CSVReader reader = new CSVReader(new FileReader(file.getAbsolutePath()));
}catch(FileNotFoundException fnfe) {
    // handle exception, e.g. show error message
}

如果问题实际上出在那一行,而不是Andreas指出的地方,那么直接用file构造FileReader而不是给它路径:

new FileReader(file)

暂无
暂无

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

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