3

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);
    }
Pops
  • 30,199
  • 37
  • 136
  • 151
Afzaal
  • 33
  • 1
  • 1
  • 3

4 Answers4

23

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

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.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
1

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.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
1

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 );
Mark Storer
  • 15,672
  • 3
  • 42
  • 80
  • Why would I suffer the pain of doing it the hard way when Sun gave me an easy option? (Did I say Sun?) :) – Buhake Sindi Nov 24 '10 at 16:54
  • In general, you wouldn't. Some sadistic teacher might have you do it both ways just so you appreciate "the easy way" that much more. This question _is_ simple enough that it might be tagged "homework". But yeah, given the option... easy way every time. – Mark Storer Nov 24 '10 at 17:42
  • To defend Mr Storer, it's good to know the hard way if there is any functional difference at all from the easy way, because there may be situations where the easy way is inadequate. Like in this case, if you need to know something about the contents of the file before you write it, like maybe you need to include a line number or a total. – Jay Nov 24 '10 at 17:49