Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android save to file.txt appending

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();
    }
}
like image 727
USER_8675309 Avatar asked Dec 12 '22 02:12

USER_8675309


2 Answers

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!

like image 95
codePG Avatar answered Jan 14 '23 10:01

codePG


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) {
    }

}
like image 34
Vibhor Chopra Avatar answered Jan 14 '23 12:01

Vibhor Chopra