bernzkie bernzkie - 2 months ago 23
Android Question

Android FIle Manipulation (APPEND)

How can I append an string into a text file? I know how to write in a text file but now I want to append using my code but it doesn't append it just writing a new string instead. Here is my code:

FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("sample.txt", Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.append("this is append text");
osw.close();
fOut.close();

} catch (Exception e) {
Toast.makeText(Ticketing.this, "Error: " + e,
Toast.LENGTH_SHORT).show();
e.printStackTrace(System.err);
return;
}


Please help!
Sorry for my bad English.
Thanks!

Answer

mmm... try this..

FileOutputStream fOut = null;
OutputStreamWriter osw = null;
String separator = System.getProperty("line.separator");
try {
    fOut = openFileOutput("sample.txt",MODE_APPEND|MODE_WORLD_READABLE);
    osw = new OutputStreamWriter(fOut);
    osw.write("this is append text");
    osw.write(separator);
    osw.flush();
    osw.close();
} catch (Exception e) {
    Toast.makeText(Ticketing.this,"Error: " + e, Toast.LENGTH_SHORT).show();
    return;

}