Search code examples
androidsd-cardfilewriterbufferedwriter

Android : Write in same file multiple times


New with Android. Sorry! I'm trying to create the following...

  1. Wait for Timer to Finish. (No issues here).
  2. Write time to a log file.
  3. Activate Timer again.
  4. Go back to step 1 & repeat.

The code for writing to the file is as follows...

    File file = new File("/sdcard/log.txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    writer.write(str);
    writer.newLine();
    writer.flush();
    writer.close();

The code is only writing the last .write in the file! The previous WRITE is removed. I suspect that its creating a new file everytime and writing the latest line. I tried with FOS and OSW but with same results! Please help, am stuck on this one for almost 48 hours.


Solution

  • Use the FileWriter in append mode.

    BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));