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 ...
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.