Search code examples
javaioprintwriter

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.


Solution

  • 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.