开发者

Android write file

After weeks of not programming开发者_如何学JAVA 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.


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


You could use the function append of the class BufferWriter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜