我正在编写一个读取 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{}
block :
try {
CSVReader reader = new CSVReader(new FileReader(file.getAbsolutePath()));
}catch(FileNotFoundException fnfe) {
// handle exception, e.g. show error message
}
关于java - 尝试读取文件时获取 java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14642264/