0
public void writePlayerTurnActions(String action){
        File file = new File(this.playerFileName);

        try {
            FileWriter writer = new FileWriter(this.playerFileName);

            if(!file.exists()) {
                file.createNewFile();
            }

            writer.write(action + "\n");
            writer.close();

        } catch (IOException e) {
            System.out.println("Error writing to player output file");
        }
    }

Here is the method im using to keep updating a file depending on what occurs during the execution of the program. Im calling it by

instance.writePlayerTurnActions("1");
instance.writePlayerTurnActions("2");
instance.writePlayerTurnActions("3");

When running this code the file only contains a 3... and not 1, 2, 3 on seperate lines.

Any help appreciated as i'm so confused as to whats going wrong...

Ben Graham
  • 65
  • 5

1 Answers1

0

you should not create a new FileWriter instance each time you want to write something (not only because of this issue, it's also very bad performance wise). Instead, keep one globally and instead of calling writer.close() when you're done writing your current String to the file, call writer.flush().

Azrael
  • 175
  • 1
  • 12