Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewriting into a file

I write a simple function like this:

private static void write(String Swrite) throws IOException {
   if(!file.exists()) {
      file.createNewFile();
   }
   FileOutputStream fop=new FileOutputStream(file);
   if(Swrite!=null)
      fop.write(Swrite.getBytes());
   fop.flush();
   fop.close();
}

Every time I call it, it rewrite and then I just get the last items that are written. How can I change it to not rewriting? The file variable is defined globally as a File.

like image 942
seventeen Avatar asked Dec 13 '11 04:12

seventeen


1 Answers

On your FileOutputStream constructor, you need to add the boolean append parameter. It will then look like this:

FileOutputStream fop = new FileOutputStream(file, true);

This tells FileOutputStream that it should append the file instead of clearing and rewriting all of its current data.

like image 54
Jon Egeland Avatar answered Sep 21 '22 03:09

Jon Egeland