This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
What is the difference between the following pieces of code?
What does it mean when the HeadFirst book says "FileWriter writes each and every thing you want to pass to the file each and every time"? I thought that it meant that the FileWriter writes to the disk file each time you call write(String s) but when I tried the following code, nothing came out on the file. So does that mean both FileWriter and BufferedWriter only write to the file when their streams are flushed? (excuse my poor technical language) If so, how is one more efficient than the other??
From the API docs for the flush() method of the Writer class,
If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.
So even though the JVM is writing out the characters immediately, the underlying OS may still be buffering them. I suspect that if you experiment with different amounts of text being written out, you'll find a point where the two classes start behaving differently from each other. Even when there is no observable difference in the outward behavior of the two classes, the BufferedWriter I/O could still be more efficient if it results in fewer calls to the OS being made.