The Java I/O framework uses wrapper classes to build
specialized I/O streams. Conceptually the aim is to provide great
flexibility and modularity by wrapping streams with classes
that provide particular capabilities as needed.
Typically an instance of a lower level class is created
and then it is wrapped inside more specialized stream instances
by passing it to the wrapper via a constructor argument. The following
code segment gives a couple of examples:
...
// Convert the 8-bit System
input to 16-bit
InputStreamReader in = new InputStreamReader (System.in);
// Wrap with in a buffer object
to speed I/O
BufferedReader
bufIn = new BufferedReader (in);
// Read the keyboard input using
the readLine method
String strLine = bufIn.readLine ();
...
|
Here we first wrap an 8-bit character stream, System.in,
with a 16-bit character Reader
class. This provides for efficienct input of non-ASCII characters.
Buffered classes improve the performance of
I/O by providing intermediate data storage buffers. The data
must fill the buffer to a certain level before
it is sent to
the next stage, thus performing fewer
time-consuming operations. Note that this can require the "flushing"
of data near the end of the transmission when the data did not
reach the level required for release.
In the above example, we wrap
the InputStreamReader with
a BufferedReader,
which not only buffers the data but also provides some useful
methods such as readLine().
With this method the input text from the command line returns
as a string rather than one character at a time as in the lower
level console classes.
Note: this use of the
term wrapper has nothing to do with the numerical wrapper
classes, which wrap primitive type values, but follow the same
pattern of adding capabilities to an object.
Latest update: Nov. 10, 2004
|