0

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?

Scoopta
  • 987
  • 1
  • 9
  • 22

1 Answers1

1

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);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Well I was hoping to avoid the constant closing and re-opening of the file because I feel like that just adds overhead but maybe not. Either way it solves my problem. The nio solution might be more what I'm looking for though. – Scoopta Aug 30 '15 at 21:29