Reputation: 835
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.
Upvotes: 5
Views: 689
Reputation: 6716
The problem is that the cursor that is marking the place where the OutputStreamWriter
is starting to write into the file is at the very beginning of the file.
What you want to do is to set it to the end of the file using the alternative constructor of FileOutputStream
that has a boolean attribute. The fixed code would be:
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();
}
}
Upvotes: 1
Reputation: 8358
use FileOutputStream's secondconstructor :
FileOutputStream(String name, boolean append)
with append value as true
Upvotes: 2
Reputation: 7462
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.
Upvotes: 7