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();
    }
}
                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!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
    try {
        String filename = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + mFileName;
        FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
        fw.write(mValue + "\n\n");
        fw.close();
    } catch (IOException ioe) {
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With