PrintWriter append method not appending

snnlankrdsm picture snnlankrdsm · Nov 21, 2011 · Viewed 82.3k times · Source

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) {...}
}

Answer

axtavt picture axtavt · Nov 21, 2011

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.