O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Subclassing OutputStream

OutputStream is an abstract class that mainly describes the operations available with any particular OutputStream object. Specific subclasses know how to write bytes to particular destinations. For instance, a FileOutputStream uses native code to write data in files. A ByteArrayOutputStream uses pure Java to write its output in a potentially expanding byte array.

Recall that there are three overloaded variants of the write() method in OutputStream, one abstract, two concrete:

public abstract void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length) throws IOException

Subclasses must implement the abstract write(int b) method. They often choose to override the third variant, write(byte[], data int offset, int length), for reasons of performance. The implementation of the three-argument version of the write() method in OutputStream simply invokes write(int b) repeatedly; that is:

public void write(byte[] data, int offset, int length) throws IOException {
  for (int i = offset; i < offset+length; i++) write(data[i]);
}

Most subclasses can provide more efficient implementations of this method. The one-argument variant of write() merely invokes write(data, 0, data.length); if the three-argument variant has been overridden, this method will perform reasonably well. However, a few subclasses may override it anyway.

Example 2.3 is a simple program called NullOutputStream that mimics the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required