• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the clarification.

@ Tom: Love your signature
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic