1

Possible Duplicate:
How to append text to an existing file in Java

I want to add data to a text file. So it's one after another...so something like:

1
2
3
<add more here>

But I don't want the text from the file to be deleted at all. This is the code i'm using atm, but it replaces what ever is in the file. Could someone please tell me how to do what I asked. Thanks.

    FileWriter fstream = new FileWriter("thefile.txt");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("blabla");
    out.close();
      }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
   }
}
Community
  • 1
  • 1
Butterflycode
  • 759
  • 2
  • 10
  • 23
  • 1
    http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – anon Nov 01 '12 at 10:06

1 Answers1

6

use this

FileWriter fstream = new FileWriter("thefile.txt",true);

the explanation

public FileWriter(String fileName, boolean append) throws IOException

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

vels4j
  • 11,208
  • 5
  • 38
  • 63
Bhavik Shah
  • 5,125
  • 3
  • 23
  • 40
  • That fixed the deleting problem thanks. I was able to do the new line thing as well just by doing out.write("\n" + "blabla"); – Butterflycode Nov 01 '12 at 10:10