Afzaal
Afzaal

Reputation: 43

How do you append to a text file instead of overwriting it in Java?

I am trying to add a line to a text file with Java. When I run my program, I mean to add a simple line, but my program is removing all old data in the text file before writing new data.

Here is the code:

 FileWriter fw = null;
  PrintWriter pw = null;
    try {
        fw = new FileWriter("output.txt");
        pw = new PrintWriter(fw);

    pw.write("testing line \n");
        pw.close();
        fw.close();
    } catch (IOException ex) {
        Logger.getLogger(FileAccessView.class.getName()).log(Level.SEVERE, null, ex);
    }

Upvotes: 4

Views: 22248

Answers (4)

Mark Storer
Mark Storer

Reputation: 15870

Two options:

  1. The hard way: Read the entire file, then write it out plus the new data.
  2. The easy way: Open the file in "append" mode: new FileWriter( path, true );

Upvotes: 1

Buhake Sindi
Buhake Sindi

Reputation: 89189

Use

fw = new FileWriter("output.txt", true);

From JavaDoc:

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Upvotes: 1

Powerlord
Powerlord

Reputation: 88826

Change this:

fw = new FileWriter("output.txt");

to this:

fw = new FileWriter("output.txt", true);

The second argument to FileWriter's constructor is whether you want to append to the file you're opening or not. This causes the file pointer to be moved to the end of the file prior to writing.

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1503280

Change this:

fw = new FileWriter("output.txt");

to

fw = new FileWriter("output.txt", true);

See the javadoc for details why - effectively the "append" defaults to false.

Note that FileWriter isn't generally a great class to use - I prefer to use FileOutputStream wrapped in OutputStreamWriter, as that lets you specify the character encoding to use, rather than using your operating system default.

Upvotes: 26

Related Questions