0

As title says, I'm trying to make the file writer write onto a new line every time I click the save button, instead it just overwrites whatever was previously saved in the file.

Code:

saveButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try{
                PrintWriter fileWriter = new PrintWriter("passwords.txt", StandardCharsets.UTF_8);
                fileWriter.print(webApp.getText());
                fileWriter.print(": ");
                fileWriter.print(pass.getText());
                fileWriter.close();
            } catch (IOException b) {
                b.printStackTrace();
            }
            pass.setText(null);
            webApp.setText(null);
        }
    });
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Rhys Keown
  • 29
  • 3

1 Answers1

1

As pointed out in comments, you should try configuring FileWriter to append mode like this:

private static void writeToFile(final String filePathName, String text) throws IOException {
    FileWriter fileWriter = new FileWriter(filePathName, true); // Set append=true
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.println(text);
    printWriter.close();
}

Calling above function repeatedly with code like this:

writeToFile("passwords.txt", "Some text");
writeToFile("passwords.txt", "Some More text");
writeToFile("passwords.txt", "Other text");

It would produce following file:

stackoverflow-code : $ cat passwords.txt 
Some text
Some More text
Other text
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40