Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrintWriter append method not appending

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) {...} } 
like image 812
snnlankrdsm Avatar asked Nov 21 '11 10:11

snnlankrdsm


People also ask

How do I append a PrintWriter?

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 .

Does FileWriter append?

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 .

When a file is open for appending Where does write () put new text?

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.

How do you append to file handling in Java?

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.


2 Answers

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.

like image 99
axtavt Avatar answered Oct 05 '22 23:10

axtavt


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

The true is the append flag. See documentation.

like image 25
Stephan Avatar answered Oct 05 '22 21:10

Stephan