0

I know that since Java 1.5 PrintWriter preforms internal buffering even if it created with PrintWriter(String fileName) constructor. So i don't need tedious decoration like this:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File")));

So I am wondering whether it still make sense to manually decorate Streams/Readers/Writers classes or PrintWriter is a particular case? For instance:

ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("File")));

In all tutorials such things declared without BufferedOutputStream. But does it really improve performance or not? Or now i can just use constructors without intermediate buffer's constructor with current I/O classes?

Dmytro
  • 1,850
  • 3
  • 14
  • 20

1 Answers1

2

Yes PrintWriter would be a particular case. It's constructor internally does

public PrintWriter(String fileName) throws FileNotFoundException {
    this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
         false);
}

but same does not happen for ObjectOutputStream and definitely cannot be generalized that decorators are not needed and can the same functionality is added in new constructor implementation. For instance -

ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("File"))); 

You are saying I want to write to a file, buffer the contents (to reduce multiple write calls) and finally you decorate the resultant OutputStream so that you can serialize/deserialize it.

Also in my opinion there should not be any performance impact with using decorators versus using the corresponding constructor because at the end of the day you are doing the same thing.

Then why in all Serialization tutorials(for example) ObjectOutputStream is created without buffering?

As for serialization ObjectOutputStream(OutputStream out) wraps the OutputStream out with BlockDataOutputStream which itself is a buffered output stream so you don't need a separate BufferedWriter.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Thanks for your answer. _'buffer the contents (to reduce multiple read calls)'_ — so that thing doesn't really improve performance? Then when buffering is useful? – Dmytro Feb 22 '15 at 05:47
  • It definitely increases performance. I was comparing the the use of decorators versus similar implementation provided in constructor. – Aniket Thakur Feb 22 '15 at 05:53
  • Then why in all Serialization tutorials(for example) `ObjectOutputStream` is created without buffering? This thing is confusing me. – Dmytro Feb 22 '15 at 05:57
  • For output streams buffering implied reducing write called (I mentioned read call earlier, my bad, that if for buffered reading). Updated answer for Serialization part. – Aniket Thakur Feb 22 '15 at 06:08