Android:附加到文件而不是覆盖

时间:2014-01-06 10:40:30

标签: java android text

我正在尝试附加到文本文件但由于某种原因它会一直覆盖它,这是我的代码:

File logFile = new File(Environment.getExternalStorageDirectory().toString(), "notifications.txt");
                try {
                if(!logFile.exists()) {
                     logFile.createNewFile();
                }

                StringBuilder text = new StringBuilder(); // build the string
                String line;
                BufferedReader br = new BufferedReader(new FileReader(logFile)); //Buffered reader used to read the file
                while ((line = br.readLine()) != null) { // if not empty continue
                    text.append(line);
                    text.append('\n');
                }
                BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
                output.write(text + "\n");
                output.close();
                alertDialog.show();
                } catch (IOException ex) {
                    System.out.println(ex);
                }

提前谢谢

2 个答案:

答案 0 :(得分:4)

使用

new FileWriter(logFile, true)

第二个参数告诉它追加,而不是覆盖。

this question.中找到右边的相关问题。

可以找到文档here

答案 1 :(得分:1)

您需要使用FileWriter的其他构造函数来指定数据是否被覆盖或追加。使用FileWriter(logFile, true)代替您现在拥有的内容:)

相关问题