0

I'm making a hangman game and the goal is to save the stats for different players, such as their name, games played, and wins. I have this part working, but every time I run the program it deletes the previous data and replaces it.

public static void writeStats(File file,String name, int won, int games) {
    try {
        PrintWriter pw = new PrintWriter(file);
        pw.println("Player\tWon\tTotal");
        pw.println("-----------------------------");
        pw.println(name+"\t"+won+"\t"+games);
        pw.close();
    } //end try
    catch (IOException e) {
        System.out.println("Failed to write file!");
    } //end catch
} //end method
Peter Neyens
  • 9,770
  • 27
  • 33
ajjohnson190
  • 494
  • 2
  • 7
  • 21
  • Possible duplicate of [How to append text to an existing file in Java](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Tom Oct 05 '15 at 14:05

1 Answers1

1

You can pass PrintWriter a Writer, and use FileWriter, which has an append flag, which will allow you to append the values to the file

Start by having a look at FileWriter

try (PrintWriter ps = new PrintWriter(new FileWriter(file, true))) {
    //...
} catch (IOException exp) {
    System.out.println("Failed to write file!");
    exp.printStackTrace();
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366