0

I want to store all the sales in a txt file, but every time I enter new information it deletes the old information. Any idea why?

try {
    BufferedWriter bfw = new BufferedWriter(new FileWriter(file1));
    BufferedWriter bfw1 = new BufferedWriter(new FileWriter(file2));

    bfw.write(Total.getText());
    bfw.newLine();

    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
    bfw1.write(timeStamp);
    bfw1.newLine();

    bfw.close();
    bfw1.close();
} catch (IOException ex) {
    Logger.getLogger(FrmFacturas.class.getName()).log(Level.SEVERE, null, ex);
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Blober
  • 3
  • 4

2 Answers2

1

You can put a second parameter to the FileWriter constructor:

BufferedWriter bfw = new BufferedWriter(new FileWriter(file1, true));

OR

you could use Files.nio:

Files.writeString(file1.toPath(), textToWrite, StandardOpenOption.APPEND)

Hias
  • 57
  • 3
0

You have to open the file in append mode to do this add true as the second parameter in FileWriter

BufferedWriter bfw = new BufferedWriter(new FileWriter(file1,true));
DarrenChand
  • 116
  • 13
  • Thank you, I tried this but It didnt work – Blober Oct 21 '20 at 21:43
  • seems like you wish to append the timestamp try using this code String textToAppend = "yourtimestamp"; //Set true for append mode BufferedWriter writer = new BufferedWriter( new FileWriter("c:/temp/samplefile.txt", true)); writer.write(textToAppend); writer.close(); – DarrenChand Oct 21 '20 at 21:49