Java IO (javase 6)- Help me understand the effects of my sample use of Streams and Writers

261 views Asked by At
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( new BufferedOutputStream( new FileOutputStream("out.txt") ) ) );

So let me see if I understand this: A byte output stream is opened for file "out.txt". It is then fed to a buffered output stream to make file operations faster. The buffered stream is fed to an output stream writer to bridge from bytes to characters. Finally, this writer is fed to a buffered writer... which adds another layer of buffering?

Hmm...

2

There are 2 answers

4
Thirler On BEST ANSWER

Yes you are correct.

I think in this case you could do a lot shorter (see also BufferedWriter)

BufferedWriter out = new BufferedWriter(new FileWriter("foo.out"));

or if you want nice printing functions:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

It is possibly that the FileWriter creates its own wrapping, but that class will know which way is best.

In java Streams and Writers are wrappers so you can assemble them to your own needs (by means of stacking them like you do). The classes don't look at what type of stream/writer they stack on. In your case having several buffers will mean you actually have two buffers, in two different classes. This means they'll take up some extra memory and possibly some performance loss, but most likely you will never notice this (because it is only a little overhead compared to other performance factors).

0
Chuk Lee On

This is an example of the decorator pattern. The idea is to add functionality to a class without modifying the class. In your example you have a FileWriter. You want whatever you write to be buffered (good idea if it is over the network) first before writing. So you layer BufferedWriter on top of FileWriter. Other apps may not want the data to be buffered so the developers will not need to add a BufferedWriter.

We cannot anticipate what all developers will need. Say you need to rot13 your data, now instead of modifying FileWriter, you create a class call Rot13Writer that implements Writer. The Rot13Writer will take a instance of Writer and will perform rot13 before passing it on to the next writer.