0

I use the following code to write text content to MessageCleanupLogs.txt, it seems that it's a overwrite mode, when I run the code again, the previously created MessageCleanupLogs.txt is overwrite.

How can I set append mode for the file MessageCleanupLogs.txt to append new content? Thanks!

       String filename=Environment.getExternalStorageDirectory() + "/MessageCleanupLogs.txt";

        try
        {
            File file = new File(filename);
            if (!file.exists()) {
                file.createNewFile();
            }

            String aa="a\r\nb\r\nb";

            FileOutputStream fOut = new FileOutputStream(filename);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append("test");
            myOutWriter.append("\r\n");
            myOutWriter.append(aa);
            myOutWriter.close();
            fOut.close();

        } catch (Exception e) {

        }
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

1

The java methods of append itself will work.

PrintWriter out = null;
    String filepath = "/sdcard/myfile.txt"; // your file path here
    String contents = "hello world"; // your file contents here
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(filepath, true)));
        out.println(contents);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

Reference from https://stackoverflow.com/a/1625263/3894784

Community
  • 1
  • 1
Harish Sridharan
  • 1,070
  • 6
  • 10