PrintWriter附加方法不附加

PrintWriter附加方法不附加

本文介绍了PrintWriter附加方法不附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下方法仅写出我添加的最新项目,它不会附加到以前的条目。我做错了什么?

The following method only writes out the latest item I have added, it does not append to previous entries. What am I doing wrong?

public void addNew() {
    try {
        PrintWriter pw = new PrintWriter(new File("persons.txt"));
        int id = Integer.parseInt(jTextField.getText());
        String name = jTextField1.getText();
        String surname = jTextField2.getText();
        Person p = new Person(id,name,surname);
        pw.append(p.toString());
        pw.append("sdf");
        pw.close();
    } catch (FileNotFoundException e) {...}
}


推荐答案

PrintWriter 的方法被称为 append()的事实不会意味着它改变了正在打开的文件的模式。

The fact that PrintWriter's method is called append() doesn't mean that it changes mode of the file being opened.

您还需要在追加模式下打开文件:

You need to open file in append mode as well:

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"),
    true /* append = true */));

另请注意,文件将以系统默认编码写入。它并不总是需要并且可能导致互操作性问题,您可能希望明确指定文件编码。

Also note that file will be written in system default encoding. It's not always desired and may cause interoperability problems, you may want to specify file encoding explicitly.

这篇关于PrintWriter附加方法不附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:12