我有一个结果正在输入到一个文件中。这个结果是在一个循环中完成的。因此,每次出现新的结果时,都必须将其附加到一个文件中,但它正在被覆盖。我应该使用什么来将我的结果附加到单个文件中?
发布于 2011-06-02 01:11:48
试一试
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
}
catch (IOException e) {
// handle exception
}
finally{
if(out != null){
try{
out.close();
}
catch(IOException e){
// handle exception
}
}
}
根据API的说法
在给定文件对象的情况下,
构造一个FileWriter对象。如果第二个参数为true,则字节将写入文件的末尾,而不是开头。
发布于 2011-06-02 01:11:50
下面是基本的代码片段
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java 1");
out.write("Hello Java 2");
另请参阅
发布于 2011-06-02 01:13:04
您应该让文件保持打开状态(有时这样会更好,但通常不会...)或者在append mode中打开输出流
OutputStream os = new FileOutputStream(file, true);
https://stackoverflow.com/questions/6205078
复制相似问题