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) {...}
}
The fact that
PrintWriter
's method is calledappend()
doesn't mean that it changes mode of the file being opened.You need to open file in append mode as well:
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.
Open the file in append mode, as with the following code:
The
true
is the append flag. See documentation.IMHO the accepted answer does not consider the fact that the intention is to write characters. (I know the topic is old, but since while searching for the same topic I stumbled upon this post before finding the advised solution, I am posting here.)
From the
FileOutputStream
docs, you useFileOutputStream
when you want to print bytes.Besides, from the
BufferedWriter
docs:Finally, the answer would be the following (as mentioned in this other StackOverFlow post):