Search code examples
javafilenotfoundexceptionprintwriter

PrintWriter is throwing FileNotFoundException


I have a method:

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();
}

And it throws this error:

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)

It says the error is in the line with PrintWriter writer = ... The file definitely exists. (but that shouldn't be a problem, should it?). This method has worked for .pngs in an ImageIcon, so I don't see why it would be any different. Could someone explain why this doesn't work and how to fix it?


Solution

  • As requested, this worked:

    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();
    }