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...
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().
Joined: Feb 18, 2010
Thank you for the clarification.
@ Tom: Love your signature
subject: PrintWriter using flush() and close() for code to work