Java Reference
In-Depth Information
The Reader / Writer classes were added in Java 1.1 to deal with 16-bit character
encoding. Java uses the 16-bit Unicode format to represent all text characters.
(We discuss Unicode and other encoding schemes in Section 9.7.)
Classes that inherit from the above abstract classes provide specialized streams
such as for keyboard input and file I/O. The Java I/O classes either extend or wrap
lower level classes to provide additional capabilities. See the java.io package
specifications in the Java 2 API Specifications for a list of its many stream and
ancillary classes.
A frequent criticism of Java I/O is that it involves too many classes. Often an
entire class, such as PushbackInputStream ,which puts data back into the
stream, is required to do a task that might well have been done by a method within
another class.
9.3 Stream wrappers
The Java I/O framework builds specialized I/O streams by combining classes
together. The goal is to provide flexibility and modularity by wrapping an instance
of a lower level stream class with an instance of a class that provides additional
features. Here wrapping refers to passing a stream object as a parameter in a
constructor of another stream class. A wrapper provides its own set of methods
for input or output operations and uses the wrapped stream internally to carry
them out.
Forexample, the following code segment shows an instance of the Input-
StreamReader class wrapping the System.in stream:
InputStreamReader in = new InputStreamReader (System.in);
This wraps an 8-bit character stream, System.in , with a 16-bit character
Reader class. This provides for more efficient handling of non-ASCII char-
acters. (See Section 9.7.)
Similarly, we can wrap an instance of InputStreamReader with a buffered
class wrapper:
BufferedReader buf - in = new BufferedReader (in);
Buffered classes improve the performance of I/O by providing intermediate data
storage buffers. The data fills the buffer to a certain level before it is sent in
bulk to the next stage, thus performing fewer time-consuming operations. (This
requires flushing at the end of the transmission to ensure that no data remains in
the buffer.)
In addition to buffering the data input, a BufferedReader provides several
useful methods. For example, the read() methods in InputStreamReader
return only one character at a time so we would need a loop to read a whole line
of characters. Instead, we can wrap this class with a BufferedReader and use
the BufferedReader.readLine() method:
String str - line = buf - in.readLine ();
Search WWH ::




Custom Search