我使用下面的代码段将文本写入文件的末尾,以便每次调用它。但是,它正在擦除旧数据,然后将新数据写入文件的开头。如何修复以下代码,以便附加新数据始终文件末尾?
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();
}
答案 0 :(得分:15)
尝试在boolean
中将FileOutputStream
值附加到true:
outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream);