This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes FileWriter vs BufferedWriter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "FileWriter vs BufferedWriter" Watch "FileWriter vs BufferedWriter" New topic

FileWriter vs BufferedWriter

Victor Lu

Joined: Jun 30, 2011
Posts: 6
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??

Kurt Van Etten
Ranch Hand

Joined: Sep 07, 2010
Posts: 98
Hi Victor,

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.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Note also that you can specify the size of the buffer used by a BufferedWriter. Try creating one with an extremely large (or small) buffer size and see what happens.
I agree. Here's the link:
subject: FileWriter vs BufferedWriter
It's not a secret anymore!