6

After weeks of not programming I've decided to finish my application. Last time I was not able to do the file writing and reading and now I want to do it. I could perhaps use databases but this seems a lot easier. I have found this page from where I copy-pasted the code. At least now I am able to check the content of the file on my phone (I am not using any virtual SD cards for the time being, but it would definitely accelerate the testing). Problem is with this code that every time I write the file, close my app and then reopen it and write the file again, the content of the file is reset.

File root = Environment.getExternalStorageDirectory();
File file = new File(root, "tomato50.txt");
if (assignArr.size() > 0) {
    try {
        if (root.canWrite()) {
            FileWriter filewriter = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(filewriter);
            for (int i = 0; i < assignArr.size(); i++) {
                out.write(assignArr.get(i) + "\n");
                Toast.makeText(MainActivity.this,
                        "out: " + assignArr.get(i), Toast.LENGTH_LONG)
                        .show();
            }
            out.close();
        }
    } catch (IOException e) {
        Log.e("TAG", "Could not write file " + e.getMessage());
    }
}

E.g.

  1. I put one item into assignArr.
  2. The item is written into the file.
  3. I close the app. AssignArr gets empty as it is a variable.
  4. I open the app.
  5. I put an item into assignArr.
  6. I close the app. AssignArr gets empty as it is a variable.
  7. I open the file which shows only the last item.
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
erdomester
  • 11,789
  • 32
  • 132
  • 234

2 Answers2

15

Use FileWriter filewriter = new FileWriter(file,true); to append data to the existing file.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • 1
    This is correct. The true is a flag to an overloaded constructor to allow for >> instead of > – Eric May 07 '11 at 15:17
1

You could use the function append of the class BufferWriter.

elyashiv
  • 3,623
  • 2
  • 29
  • 52