Add text to end of file

I use the code segment below to write text to the end of a file each time it is called. But it erases the old data and then writes the new data to the beginning of the file. How can I fix the code below to always add new data to the 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();
   }        
+5
source share
1 answer

Try setting append booleantrue to FileOutputStream:

outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream); 
+14
source

All Articles