Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android write file

Tags:

file

android

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.
like image 502
erdomester Avatar asked May 07 '11 14:05

erdomester


2 Answers

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

like image 100
MByD Avatar answered Oct 13 '22 13:10

MByD


You could use the function append of the class BufferWriter.

like image 40
elyashiv Avatar answered Oct 13 '22 12:10

elyashiv