Java FileWriter - Append Line of Text File
Asked Answered
C

2

7

I have a button in a GUI, and when the button is pressed the user has the ability to add information to a text file. I have this part setup fine, but the thing that is messing with me is that when the user writes to the file it erases all the info in the text file and the only line left is the new one that was just added. I need to add the information and still keep the original info in the text file. I thought the append command was able to do this, but I'm obviously doing something wrong. Any help would be awesome!

Here's my code:

FileWriter fWriter = null;
    BufferedWriter writer = null;
    try {
        fWriter = new FileWriter("info.txt");
        writer = new BufferedWriter(fWriter);


        writer.append(javax.swing.JOptionPane.showInputDialog(this, "add info"));
        writer.newLine();
        writer.close();
    } catch (Exception e) {
    }
Conley answered 10/4, 2011 at 18:8 Comment(0)
B
11

Use the constructor that takes a bool append parameter. See the javadocs for FileWriter for that.

fWriter = new FileWriter("info.txt", true);
Backwater answered 10/4, 2011 at 18:12 Comment(1)
here (sun JVM @ ubuntu), it looks like when FileWriter("info.txt") alone is used, append is preferred. Any chances that woudld be platform-dependent without actual warning in the "default" constructor's documentation ?Patrinapatriot
I
2

You need writer.flush(). PrintWriter are auto flush by default but not Writers

Impossibly answered 10/4, 2011 at 18:11 Comment(1)
close() will flush, there's no need for it here.Backwater

© 2022 - 2024 — McMap. All rights reserved.