Search code examples
javafile-ioprintwriter

PrintWriter overwrite data


I'm trying to keep track of a high score in a game I'm making by doing:

PrintWriter out = new PrintWriter(new File("path"));
while(gameLoop) {
    out.write(highScore);
    out.flush();
}

It keeps appending the data to the end of the file. I am aware I could out.close(); and then out = new PrintWriter(new File("path")); but that seems like a lot of excess code. Constantly closing and re-opening the file to achieve overwrite. Is there any way for my PrintWriter to overwrite the data without closing and re-opening the file?


Solution

  • First, I would suggest you use print (or println) with a PrintWriter. Next, if I understand your question, you could use a try-with-resources Statement and something like

    while (gameLoop) {
        try (PrintWriter out = new PrintWriter(new File("path"))) {
            out.println(highScore);
        }
    }
    

    which will close and re-open the PrintWriter on every iteration of the loop. Alternatively, you could use nio and something like

    Path file = Paths.get("path");  
    while (gameLoop) {
        byte[] buf = String.valueOf(highScore).getBytes();
        Files.write(file, buf);
    }