• 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

FileWriter vs BufferedWriter

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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??

 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 28235
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic