Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

append method of PrintWriter  RSS feed

 
Sreedevi Vinod
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi I tried to append to an existing file using the append method of the PrintWriter class in Java 5.0. But it is not working.
Here is the code I used.

PrintWriter pw=new PrintWriter("a.txt");
pw.append("xxx");
pw.close();

Please advice.

Thanks
Devi
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All the PrintWriter convenience constructors that take a File or filename as an argument truncate any existing file to zero length. If you want to open the file for appending, you have to explicitly open it in "append" mode:

PrintWriter pw = new PrintWriter(new FileWriter("a.txt", true));
 
Sreedevi Vinod
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Thanks Ernest !
But then what is the purpose of having an append method ?
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The documentation says that the append methods work exactly the same as the matching write records. The only difference is that the append methods participate in implementing the Appendable interface and the write methods don't.

So next question, what is the purpose of implementing the Appendable interface? Well, reading the documentation again, it says "The Appendable interface must be implemented by any class whose instances are intended to receive formatted output from a Formatter." What's a Formatter? It's the new feature in Java 5 which implements that "printf" method. So it can printf to anything that implements Appendable, which includes objects such as StringBuffer and PrintWriter.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would also note that Appendable was created for JDK 5, and existing classes like PrintWriter and StringBuffer were changed to implement the new interface even though they didn't implement it previously. Originally PrintWriter had no append() method, but it had a very similar method, write(). If Sun had not needed to maintain compatibility with the existing classes, they probably would have simply changed the write() method to be named append() instead. (Or vice versa.) But since many people were already using write(), they had to leave the existing method, and add a new one with the same functionality under a different name. That's why there are two methods there.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!