将文本附加到文件末尾

时间:2013-02-14 10:15:28

标签: android

我使用下面的代码段将文本写入文件的末尾,以便每次调用它。但是,它正在擦除旧数据,然后将新数据写入文件的开头。如何修复以下代码,以便附加新数据始终文件末尾?

public boolean writeToFile(String directory, String filename, String data ){
    File out;
    OutputStreamWriter outStreamWriter = null;
    FileOutputStream outStream = null;

    out = new File(new File(directory), filename);

    if ( out.exists() == false ){
                out.createNewFile();
    }

    outStream = new FileOutputStream(out) ;
    outStreamWriter = new OutputStreamWriter(outStream); 

    outStreamWriter.append(data);
    outStreamWriter.flush();
   }        

1 个答案:

答案 0 :(得分:15)

尝试在boolean中将FileOutputStream值附加到true:

outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream);