7

I am using the below code segment to write text to the end o the file for each time it is called. But, it is erasing the old data and then writes the new data to the beginning of the file. How can I fix the below code so that it is append new data always end of the file ?

public boolean writeToFile(String directory, String filename, String data ){
    File out;
    OutputStreamWriter outStreamWriter = null;
    FileOutputStream outStream = null;

    out = new File(new File(directory), filename);

    if ( out.exists() == false ){
                out.createNewFile();
    }

    outStream = new FileOutputStream(out) ;
    outStreamWriter = new OutputStreamWriter(outStream); 

    outStreamWriter.append(data);
    outStreamWriter.flush();
   }        
mavzey
  • 379
  • 1
  • 5
  • 13
  • Have you looked at http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – Wizche Feb 14 '13 at 10:16

1 Answers1

18

Try to set append boolean value to true in FileOutputStream:

outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream); 
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106