PrintWriter 抛出 FileNotFoundException

PrintWriter is throwing FileNotFoundException

我有一个方法:

try {
    PrintWriter writer = new PrintWriter(new File(getResource("save.txt").toString()));

    writer.println("level:" + level);
    writer.println("coins:" + coins);

    writer.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

它抛出这个错误:

java.io.FileNotFoundException: file:/Users/lpasfiel/Desktop/Java%20Games/Jumpo/out/production/Jumpo/com/salsagames/jumpo/save.txt (No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at java.io.PrintWriter.<init>(PrintWriter.java:263)
at com.salsagames.jumpo.Variables$Methods.save(Variables.java:49)

它说错误在 PrintWriter writer = ... 行中 该文件确实存在。 (但这应该不是问题,不是吗?)。此方法适用于 ImageIcon 中的 .pngs,所以我不明白为什么会有任何不同。有人可以解释为什么这不起作用以及如何解决它吗?

让我们仔细看看这一行:

java.io.FileNotFoundException: file:/Users/lpasfiel/Desktop/Java%20Games/Jumpo/out/production/Jumpo/com/salsagames/jumpo/save.txt (No such file or directory)

如果您查看 FileNotFoundException 的其他示例,您会发现典型的消息如下所示:

java.io.FileNotFoundException: /some/path/to/file.txt (No such file or directory)

java.io.FileNotFoundException: dir/file.txt (No such file or directory)

简而言之,典型的 "file not found" 消息以绝对或相对文件路径名开头。但在您的示例中,消息显示 "file:" URL。

我认为 是问题所在。我认为您使用 URL 字符串而不是路径名创建了 FileFile 构造函数不检查 this1,但是当您尝试实例化 FileWriter 时,OS 抱怨找不到文件 与那个路径名.

(线索是假定的路径名​​以 "file:" 开头,并且它还包含一个 %-转义的 space。)

解决方案:

类似于以下内容之一...取决于 getResource() 返回的内容。

  File file = new File(getResource("save.txt").toURI());
  PrintWriter writer = new PrintWriter(file);

  PrintWriter writer = new PrintWriter(getResource("save.txt").openStream());

1 - 它不应该。 URL 字符串实际上是语法上有效的路径名。由于允许 File 表示文件系统中不存在的文件路径,因此 File 构造函数没有理由拒绝 URL 字符串。

按照要求,这有效:

try {
    PrintWriter writer = new PrintWriter(new File(getResource("save.txt").toURI()));

    writer.println("level:" + level);
    writer.println("coins:" + coins);

    writer.close();
} catch (FileNotFoundException | URISyntaxException e) {
    e.printStackTrace();
}