1

I am trying to write an array of string into the external storage of Android emulator. Here is my code:

private void writeToFile(String[] data) {
    File workingDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/wordlist.txt");
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(workingDir))) {
        for (String line : data) {
            bw.write(line + "\n");
        }
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It did managed to write each of the item in string array into the text file. However, the next time when I execute this function again, it wipes all the previous existing strings in the text file and replaced them instead. Any ideas on how to keep append new strings to the end of the file?

Thanks!

QWERTY
  • 2,303
  • 9
  • 44
  • 85

2 Answers2

0

I solved it already. Basically I need to read all the existing text from the text file, add them to a new list, then append the latest string onto the new list, then proceed to write to the text file.

QWERTY
  • 2,303
  • 9
  • 44
  • 85
0

You can use the append option to append to the existing file without overwriting it.

BufferedWriter bw = new BufferedWriter(new FileWriter(workingDir, true))

The optional true argument sets the file writer to append mode. Also see the answers here.

Tyler V
  • 9,694
  • 3
  • 26
  • 52