Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot append text to File

Tags:

java

android

My code is :

if(myfile.exists()) {
    try {
        FileOutputStream fOut = new FileOutputStream(myfile);
        OutputStreamWriter myOutWriter =  new OutputStreamWriter(fOut);
        for (LatLng item : markerArrayList) {
            myOutWriter.append(item.toString());
        }
        myOutWriter.append("\n\n");
        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(), "Done writing ", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }        
}

When I use myOutWriter.append, what really happens is that every time I'm writing to the file, it overwrites previous content.

like image 816
vicolored Avatar asked Jun 05 '15 07:06

vicolored


1 Answers

That's because you do not use the append option of the FileOutputStream constructor.

You should use:

FileOutputStream fOut = new FileOutputStream(myfile, true);

instead, to open the file for appending.

Otherwise, it overwrites the contents of the previous file.

like image 194
vefthym Avatar answered Oct 13 '22 09:10

vefthym