Neil Jones
Neil Jones

Reputation: 41

Cant get PrintWriter to work

I'm creating a save game file for a game but my PrintWriter just overwrites the file with nothing instead of the numbers I need.

Here's the code:

public void fileWriter() throws FileNotFoundException {
    PrintWriter print = new PrintWriter(new File("C:\\Users\\john\\Desktop\\stats.txt"));
    print.print(String.valueOf(this.swordNumber) + " ");
    print.print(String.valueOf(this.shieldNumber) + " ");
    print.print(String.valueOf(this.monstersDefeated) + " ");
    print.print(String.valueOf(this.damageDealt));
}

I've tried everything to get these variables printed including String.valueOf but its not working.

Upvotes: 0

Views: 76

Answers (2)

janos
janos

Reputation: 124646

You didn't close the stream before exiting, and it didn't get flushed and closed properly. Add this line when you're done writing:

print.close();

You should always close file handles after using them.

Even better, wrap the whole thing in a try-with-resources:

try (PrintWriter writer = new PrintWriter(new File("C:\\Users\\john\\Desktop\\stats.txt"))) {
    // ...
}

That way you don't have to worry about closing it, and therefore you can never "forget" it.

Upvotes: 2

olee
olee

Reputation: 747

You should properly use Java's resource try-catch blocks. This will automatically close the stream even if any exception is thrown:

public void fileWriter() throws FileNotFoundException {
    File file = new File("C:\\Users\\john\\Desktop\\stats.txt");
    try (PrintWriter print = new PrintWriter(file)) {
        print.print(Integer.toString(swordNumber) + " ");
        print.print(Integer.toString(shieldNumber) + " ");
        print.print(Integer.toString(monstersDefeated) + " ");
        print.print(Integer.toString(damageDealt));
    }
}

Also rather than String.valueOf() I suggest using Integer.toString() instead to make the type conversion more obvious.

Upvotes: 5

Related Questions