views:

62

answers:

2
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...

+3  A: 

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).

Thirler
Yes, but in my example what does having two layers of buffering do?
Daddy Warbox
I've edited the post to reply to your question.
Thirler
Nothing useful, I guess. Probably, extra memory consumption. Benchmark if you are really interested.
Rorick
That's what I guessed. Now I'm wondering if getting rid of the BufferedWriter and leaving the BufferedOutputStream would be better than its inverse...Aw well, I was just curious. Thanks anyway.
Daddy Warbox
The above was copied from the official api. So you should use that. (It doesn't create any explicit Streams, so the actual FileWriter can do what is most efficient).
Thirler
A: 

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.

Chuk Lee