jQuery in Action, 2nd edition*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "FileWriter vs BufferedWriter" Watch "FileWriter vs BufferedWriter" New topic
Author

FileWriter vs BufferedWriter

Victor Lu
Greenhorn

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
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

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.
 
 
subject: FileWriter vs BufferedWriter
 
Similar Threads
Unexpected Behaviour with Writers
problem with file writing
Write to a txt. file, via user input? (java with netbeans)
Missing import statment
flush()