您如何附加到文本文件而不是在 Java 中覆盖它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4269302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:37:32  来源:igfitidea点击:

How do you append to a text file instead of overwriting it in Java?

java

提问by Afzaal

I am trying to add a line to a text file with Java. When I run my program, I mean to add a simple line, but my program is removing all old data in the text file before writing new data.

我正在尝试使用 Java 在文本文件中添加一行。当我运行我的程序时,我的意思是添加一个简单的行,但我的程序在写入新数据之前删除了文本文件中的所有旧数据。

Here is the code:

这是代码:

 FileWriter fw = null;
  PrintWriter pw = null;
    try {
        fw = new FileWriter("output.txt");
        pw = new PrintWriter(fw);

    pw.write("testing line \n");
        pw.close();
        fw.close();
    } catch (IOException ex) {
        Logger.getLogger(FileAccessView.class.getName()).log(Level.SEVERE, null, ex);
    }

回答by Jon Skeet

Change this:

改变这个:

fw = new FileWriter("output.txt");

to

fw = new FileWriter("output.txt", true);

See the javadocfor details why - effectively the "append" defaults to false.

有关原因的详细信息,请参阅javadoc- 实际上“附加”默认为 false。

Note that FileWriterisn't generally a great class to use - I prefer to use FileOutputStreamwrapped in OutputStreamWriter, as that lets you specify the character encoding to use, rather than using your operating system default.

请注意,这FileWriter通常不是一个好用的类 - 我更喜欢使用FileOutputStreamwrapped in OutputStreamWriter,因为它允许您指定要使用的字符编码,而不是使用您的操作系统默认值。

回答by Powerlord

Change this:

改变这个:

fw = new FileWriter("output.txt");

to this:

对此:

fw = new FileWriter("output.txt", true);

The second argument to FileWriter's constructoris whether you want to append to the file you're opening or not. This causes the file pointer to be moved to the end of the file prior to writing.

FileWriter构造函数的第二个参数是您是否要附加到您正在打开的文件中。这会导致文件指针在写入之前移动到文件末尾。

回答by Buhake Sindi

Use

利用

fw = new FileWriter("output.txt", true);

From JavaDoc:

JavaDoc

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

给定一个 File 对象构造一个 FileWriter 对象。如果第二个参数为真,则字节将写入文件的末尾而不是开头。

回答by Mark Storer

Two options:

两种选择:

  1. The hard way: Read the entire file, then write it out plus the new data.
  2. The easy way: Open the file in "append" mode: new FileWriter( path, true );
  1. 困难的方法:读取整个文件,然后将其连同新数据一起写出。
  2. 简单的方法:以“追加”模式打开文件: new FileWriter( path, true );