如何设置追加模式将内容附加到android中的文本文件?

时间:2015-06-25 02:38:57

标签: android

我使用以下代码将文本内容写入MessageCleanupLogs.txt,似乎它是一种覆盖模式,当我再次运行代码时,先前创建的MessageCleanupLogs.txt将被覆盖。

如何为MessageCleanupLogs.txt文件设置追加模式以追加新内容?谢谢!

       String filename=Environment.getExternalStorageDirectory() + "/MessageCleanupLogs.txt";

        try
        {
            File file = new File(filename);
            if (!file.exists()) {
                file.createNewFile();
            }

            String aa="a\r\nb\r\nb";

            FileOutputStream fOut = new FileOutputStream(filename);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append("test");
            myOutWriter.append("\r\n");
            myOutWriter.append(aa);
            myOutWriter.close();
            fOut.close();

        } catch (Exception e) {

        }

1 个答案:

答案 0 :(得分:1)

追加自身的java方法将起作用。

PrintWriter out = null;
    String filepath = "/sdcard/myfile.txt"; // your file path here
    String contents = "hello world"; // your file contents here
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(filepath, true)));
        out.println(contents);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

来自https://stackoverflow.com/a/1625263/3894784

的参考资料