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 implements all of the print() methods found in PrintStream , so we can use all formats which you use with System. out. println() statements. To append content to an existing file, open the writer in append mode by passing the second argument as true .
FileWriter takes an optional second parameter: append . If set to true, then the data will be written to the end of the file. This example appends data to a file with FileWriter .
You can use FileWriter to open the file for appending text as opposed to writing text. The difference between them is that when you append data, it will be added at the end of the file. Since FileWriter writes one character at a time, it's better to use BufferedWriter class for efficient writing.
We can append to file in java using following classes. If you are working on text data and the number of write operations is less, use FileWriter and use its constructor with append flag value as true . If the number of write operations is huge, you should use the BufferedWriter.
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 pw = new PrintWriter(new FileOutputStream(new File("persons.txt"),true));
The true
is the append flag. See documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With