文件编写器覆盖文件而不是附加到末尾的问题 [英] Trouble with filewriter overwriting files instead of appending to the end

查看:29
本文介绍了文件编写器覆盖文件而不是附加到末尾的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我在将多行写入文本文件时遇到了一些问题.

OK, I'm having some trouble writing multiple lines to a text file.

程序运行,但不会每次都使用新行

the program runs, but it won't use new lines each time

当我希望它运行 4 次时,文本文件应如下所示:

when I want it run 4 times, the text file should look like:

a
b
c
d

相反,它看起来像:

d

谁知道如何解决这个问题?所有导入均已正确导入.

who knows how to fix this problem? all imports are correctly imported.

源代码(略有编辑,假设一切都已正确定义):

source(it's been slightly edited, assume everything is properly defined):

import java.io.*;
public class Compiler {
public static void main (String args[]) throws IOException
{
    //there's lots of code here
    BufferedWriter outStream= new BufferedWriter(new FileWriter("output.txt"));
    outStream.newLine();
    outStream.write(output);
    outStream.close();
}

}

推荐答案

确保在创建 FileWriter 的实例时,将其附加到它的末尾.这可以通过使用 这个特定的 FileWriter 构造函数,它需要一个额外的 boolean 作为第二个参数.这个 boolean 告诉 FileWriter 附加到文件的末尾,而不是覆盖文件.

Make sure that when you create an instance of a FileWriter, that you are appending to the end of it. This can be done by using this specific FileWriter constructor which takes an additional boolean as a second parameter. This boolean tells the FileWriter to append to the end of the file, rather than overwriting the file.

BufferedWriter outStream= new BufferedWriter(new FileWriter("encoded.txt", true));

这篇关于文件编写器覆盖文件而不是附加到末尾的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆