• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for the clarification.

@ Tom: Love your signature
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic