Java Reference
In-Depth Information
Byte-oriented I/O is done with stream classes that extend
InputStream
or
OutputStream
.
InputStream
and
OutputStream
are abstract classes and not inter-
faces, so there is no such thing as a stream open for both input and output.
These classes declare an abstract
read
and
write
method for single-byte I/O,
respectively, and also a small set of concrete methods such as
close
and block
I/O (which can be implemented in terms of calls to single-byte I/O). Exam-
ples of these classes include
FileInputStream
and
FileOutputStream
, as well as
the hidden
SocketInputStream
and
SocketOutputStream
. (The socket streams are
produced by methods that return an object statically typed as
InputStream
or
OutputStream
.)
Character-oriented I/O is done with classes that extend the abstract classes
Reader
and
Writer
. These also contain
read
and
write
methods. There are not as
many
Reader
and
Writer
classes as
InputStream
and
OutputStream
classes.
However, this is not a problem, because of the
InputStreamReader
and
OutputStreamWriter
classes. These are called
bridges
because they cross over
from the
Stream
to
Reader
and
Writer
hierarchies. An
InputStreamReader
is con-
structed with any
InputStream
and creates an object that
IS-A
Reader
. For
instance, we can create a
Reader
for files using
InputStreamReader
and
OutputStream-
Writer
classes are
bridges
that allow
the programmer to
cross over from
the
Stream
to
Reader
and
Writer
hierarchies.
InputStream fis = new FileInputStream( "foo.txt" );
Reader fin = new InputStreamReader( fis );
It happens that there is a
FileReader
convenience class that does this
already; Figure 4.20 provides a plausible implementation.
From a
Reader
, we can do limited I/O; the
read
method returns one charac-
ter. If we want to read one line instead, we need a class called
BufferedReader
.
Like other
Reader
objects, a
BufferedReader
is constructed from any other
Reader
, but it provides both buffering and a
readLine
method. Thus, continuing
the previous example,
BufferedReader bin = new BufferedReader( fin );
Wrapping an
InputStream
inside an
InputStreamReader
inside a
BufferedReader
works for any
InputStream
, including
System.in
or sockets. Figure 4.21, which
mimics Figure 2.17, illustrates the use of this pattern to read two numbers from
the standard input.
figure 4.20
The
FileReader
convenience class
1
class FileReader extends InputStreamReader
2
{
3
public FileReader( String name ) throws FileNotFoundException
4
{ super( new FileInputStream( name ) ); }
5
}
Search WWH ::
Custom Search