Android save to file.txt appending

USER_8675309 picture USER_8675309 · Dec 11, 2014 · Viewed 11.1k times · Source

I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).

public void saveText(View view){

    try {
        //open file for writing
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));

        //write information to file
        EditText text = (EditText)findViewById(R.id.editText1);
        String text2 = text.getText().toString();
        out.write(text2);
        out.write('\n');

        //close file

        out.close();
        Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();

    } catch (java.io.IOException e) {
        //if caught
        Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
    }
}

Answer

codePG picture codePG · Dec 11, 2014

Change this,

OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));

to,

OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));

This will append your new contents to the already existing file.

I Hope it helps!