英文:
How to fix a FileNotFoundException?
问题
我试图从我的桌面读取一个文件,但是以下代码总是抛出一个FileNotFoundException
异常:
try {
Scanner fileIn = new Scanner(new FileReader("project.csv"));
} catch (FileNotFoundException e) {
// 总是会抛出异常。
}
我该如何修复这个问题?
英文:
I am trying to read a file from my desktop, but the following code always throws a FileNotFoundException
:
try {
Scanner fileIn = new Scanner(new FileReader("project.csv"));
} catch (FileNotFoundException e) {
// The exception is always thrown.
}
How do I fix this?
答案1
得分: 0
new FileReader("project.csv")
告诉读取器在当前工作目录中搜索文件,这很可能是您的用户文件夹。要在桌面上获取文件,可以使用:
new FileReader("/desktop/project.csv")
但为了安全起见,我建议使用绝对路径,还包括用户目录的路径:
new FileReader(System.getProperty("user.home") + "/desktop/project.csv")
英文:
new FileReader("project.csv")
tells the reader to search for the file in the current working directory, which is most likely your user folder. To get files on the desktop, do:
new FileReader("/desktop/project.csv")
But just to be safe, I would use the absolute path and include the one to the user directory as well:
new FileReader(System.getProperty("user.home") + "/desktop/project.csv")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论