如何修复 FileNotFoundException?

huangapple go评论106阅读模式
英文:

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")

huangapple
  • 本文由 发表于 2020年4月9日 00:51:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/61105858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定