60

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) {...}
}
javanna
  • 59,145
  • 14
  • 144
  • 125
snnlankrdsm
  • 1,401
  • 5
  • 19
  • 29

5 Answers5

106

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.

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • This is like awakening the sleeping thread, so sorry for that. But i have a doubt. how would i do append operation in file if i am given only File object, and i am not allowed to use Stream classes( e.g FileOutputStream and so on). What i am allowed is : Printwriter pw = new PrintWriter(file); : I tried append(), write(), print(). is there any readymade method for appending in this scenario. –  Apr 11 '13 at 16:43
  • As a clarification, the 'append()' method of PrintWriter refers to the fact that it is appending to the Writer i.e itself i.e it's own outputstream, and not to the file. – Abraham Philip May 26 '15 at 06:10
  • And with reference to @user1707035's question, no, it looks like you can't use a PrintWriter to append without constructing it with an OutputStream object. This is because the PrintWriter open the stream at the time of it's instantiation, and the only constructors that support File or filename as an argument open the File by internally constructing an OutputStream object without the 'append' parameter. Reference (docs): https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.File) – Abraham Philip May 26 '15 at 06:15
19
PrintWriter pw = new PrintWriter(new FileOutputStream(new File("persons.txt"),true));

The true is the append flag. See documentation.

Stephan
  • 4,395
  • 3
  • 26
  • 49
14

IMHO the accepted answer does not consider the fact that the intention is to write characters.

From the FileOutputStream docs, you use FileOutputStream when you want to print bytes.

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

Besides, from the BufferedWriter docs:

Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.

Finally, the answer would be the following (as mentioned in this other StackOverFlow post):

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
}catch (IOException e) {
    System.err.println(e);
}finally{
    if(out != null){
        out.close();
    }
} 

Also, as of Java 7, you can use a try-with-resources statement. No finally block is required for closing the declared resource(s) because it is handled automatically, and is also less verbose:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
}catch (IOException e) {
    System.err.println(e);
}
marcelocra
  • 2,094
  • 2
  • 24
  • 37
13

Open the file in append mode, as with the following code:

 PrintWriter pw = new PrintWriter(new FileOutputStream(new File("persons.txt"), true)); 
apaderno
  • 28,547
  • 16
  • 75
  • 90
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
4

You need not to double buffering as shown in all other answers. You can simply do

PrintWriter pw = new PrintWriter(new FileWriter("persons.txt",true));
Ajith
  • 1,447
  • 2
  • 17
  • 31