Java Reference
In-Depth Information
ByteArrayOutputStream byte - out = new ByteArrayOutputStream ();
DataOutputStream data - out = new DataOutputStream (byte - out);
The byte array from the stream can be obtained with
byte - out.toByteArray ();
In Section 9.13.1 we see that these techniques are useful for I/O with our histogram
classes where we want to save a mix of data types into one big byte array. Also,
in Chapter 23 we discuss serial I/O with a Java hardware processor that requires
low-level I/O with bytes. In an example, we use a byte array stream to convert a
set of data bytes to wider types.
9.11 Sources, destinations, and filters
We have seen that I/O stream classes can represent sources of input data and des-
tinations for output data. For example, disk files become sources via FileIn-
putStream and a byte array can become the destination of a stream via the
ByteArrayOutputStream class.
We emphasized that wrapper classes add greater functionality to the streams
they contain. However, you can also look at many of the wrapper classes as filters.
A stream filter monitors, transforms, or is some way processes the data as the
stream flows through it. The BufferedInputStream and BufferedOut-
putStream classes, for example, hold data in buffers until they are full before
letting the data out. They extend the classes named FilterInputStream and
FilterOutputStream , respectively (see Figure 9.1).
The FilterIntputStream class wraps an InputStream object passed
via its constructor:
protected FilterInputStream (InputStream in - stream)
The FilterInputStream class overrides all of the same methods in
InputStream but they simply invoke the corresponding methods in the
in - stream object. The FilterInputStream does nothing itself and is meant
to be extended. A subclass overrides some or all of the methods to carry out the
desired action on the data. For example, BufferedInputStream overrides all
but one of the read() methods in FilterInputStream . Similarly, Filter-
OutputStream is intended to be subclassed by a class such as BufferedOut-
putStream that overrides some or all of its methods to carry out operations on
the outgoing data.
Java I/O can be somewhat overwhelming at first but it allows for a great deal of
modularity and high-level abstraction that can actually bring clarity to program
design. For example, we will discuss in Section 9.13 how to make histograms
Search WWH ::




Custom Search