Search code examples
javaiobuffering

I/O classes buffering


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?


Solution

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