user43051
user43051

Reputation: 345

Android: Append to file instead of ovewriting

I am trying to append to a text file but for some reason it keeps overwriting it, here's my code:

File logFile = new File(Environment.getExternalStorageDirectory().toString(), "notifications.txt");
                try {
                if(!logFile.exists()) {
                     logFile.createNewFile();
                }

                StringBuilder text = new StringBuilder(); // build the string
                String line;
                BufferedReader br = new BufferedReader(new FileReader(logFile)); //Buffered reader used to read the file
                while ((line = br.readLine()) != null) { // if not empty continue
                    text.append(line);
                    text.append('\n');
                }
                BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
                output.write(text + "\n");
                output.close();
                alertDialog.show();
                } catch (IOException ex) {
                    System.out.println(ex);
                }

thank you in advance

Upvotes: 0

Views: 64

Answers (2)

Ogen
Ogen

Reputation: 6709

You need to use the other constructor of FileWriter that specifies whether the data is overwritten or appended. Use FileWriter(logFile, true) instead of what you have now :)

Upvotes: 1

IAmGroot
IAmGroot

Reputation: 13855

use

new FileWriter(logFile, true)

Where the second parameter tells it to append, not overwrite.

Found in this question. In the related questions on the right.

Documentation can be found here

Upvotes: 4

Related Questions