开发者

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

I am trying to add 开发者_如何学JAVAa 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.

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);
    }


Change this:

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

to

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

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

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


Change this:

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

to this:

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

The second argument to FileWriter's constructor is 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.


Use

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

From 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.


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 );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜