This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes PrintWriter using flush() and close() for code to work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "PrintWriter using flush() and close() for code to work" Watch "PrintWriter using flush() and close() for code to work" New topic
Author

PrintWriter using flush() and close() for code to work

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Good Morning,

Chapter 6 of Sierra/Bates has the code which I tried, and it works:



However, when I comment out



The code does not write to the file. In other words, after I compile and run the code, the file is created, but it is BLANK.

Please explain what is going on.

Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9307
    
  17

The documentation of PrintWriter says it all. The PrintWriter(Writer) constructor creates a writer which is not automatically flushed. If you don't want to call flush and close, you'll have to create your PrintWriter as
PrintWriter pw = new PrintWriter(fw,true);
The true passed to the constructor will cause the output to be flushed to the file after each call to println method...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
Calling pw.println("howdy") just gives the "howdy" data to the PrintWriter. It does not automatically write the data to the file (it buffers it). Calling flush() tells PrintWriter to write the buffered data to the file (actually it tells FileWriter to write the data to the file). Calling close() tells PrintWriter to clean up its resources. Close() also does a flush, so you don't necessarily need to call flush(). You should always call close(). And you should call close() in a finalize block to ensure you always call it (even if an exception is thrown). BTW, you can also use a different PrintWriter constructor that will tell PrintWriter to flush every time you call pw.println(). But always call close().
Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Thank you for the clarification.

@ Tom: Love your signature
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: PrintWriter using flush() and close() for code to work