【问题标题】:Getting java.io.FileNotFoundException when trying to read a file尝试读取文件时出现 java.io.FileNotFoundException
【发布时间】:2013-02-01 08:26:37
【问题描述】:

我正在编写一个读取 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());

                }
            }
        });

【问题讨论】:

  • 异常的确切信息是什么? System.out.println(e.getMessage()); 这应该可以很好地提示问题所在。它可能是“权限被拒绝”,或“系统找不到指定的文件”,或其他。这可能会提供有趣的信息,而不是人们疯狂猜测问题可能是什么。

标签: java swing jfilechooser filenotfoundexception opencsv


【解决方案1】:
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


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

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

【讨论】:

  • 加上默认目录应该是用户的主目录。
  • 我在使用 ~/ 时没有遇到任何问题,但感谢您指出这一点。
  • 有趣的是,它实际上似乎可以工作 - 在带有 Java 7 的 Windows 7 中,它会将我引导到“我的文档”文件夹。让我们检查一下文档...
  • @ChaoticLoki 回到你的问题;)我想用真实的现有路径替换“~/”并不能解决你的问题,对吧?你在new FileReader() 之前检查过System.err.println(file.getAbsolutePath()) 吗?它是否指向现有文件?
  • 我在 GUI fileLocation.setText(file.getAbsolutePath()); 中添加了这个,它打印出绝对路径没问题,这是 FileReader 的问题。
【解决方案2】:

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

new FileReader(file)

【讨论】:

  • 我删除了.getAbsoluteValue(),但它仍然抛出异常
  • 在尝试实例化FileReader 之前,尝试调试/打印并检查file.getAbsolutePath() 的值。问题的根源可能就在那里。
  • 我已经这样做了,它返回绝对路径绝对没问题。
猜你喜欢
  • 2014-12-28
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多