Unable to add text to file

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 write to a file, it overwrites the previous content.

+5
source share
3 answers

This is because you are not using the append parameter of the FileOutputStream constructor.

You should use:

 FileOutputStream fOut = new FileOutputStream(myfile, true); 

instead, to open the file to add.

Otherwise, it overwrites the contents of the previous file.

+7
source

use the second constructor of FileOutputStream:

FileOutputStream(String name, boolean append)

adding value as true

+2
source

The problem is that the cursor, indicating the place where the OutputStreamWriter to the file, OutputStreamWriter at the very beginning of the file.

What you want to do is set it to the end of the file using the alternative FileOutputStream constructor, which has a boolean attribute, Fixed code:

 if(myfile.exists()) { try { FileOutputStream fOut = new FileOutputStream(myfile, true); 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(); } } 
+1
source

All Articles