Java Reference
In-Depth Information
In this mirror image hierarchy, two abstract superclasses define the basic API for reading
and writing characters. The
java.io.Reader
class specifies the API by which characters
are read. The
java.io.Writer
class specifies the API by which characters are written.
Wherever input and output streams use bytes, readers and writers use Unicode char‐
acters. Concrete subclasses of
Reader
and
Writer
allow particular sources to be read
and targets to be written. Filter readers and writers can be attached to other readers and
writers to provide additional services or interfaces.
The most important concrete subclasses of
Reader
and
Writer
are the
InputStream
Reader
and the
OutputStreamWriter
classes. An
InputStreamReader
contains an un‐
derlying input stream from which it reads raw bytes. It translates these bytes into Uni‐
code characters according to a specified encoding. An
OutputStreamWriter
receives
Unicode characters from a running program. It then translates those characters into
bytes using a specified encoding and writes the bytes onto an underlying output stream.
In addition to these two classes, the
java.io
package provides several raw reader and
writer classes that read characters without directly requiring an underlying input
stream, including:
•
FileReader
•
FileWriter
•
StringReader
•
StringWriter
•
CharArrayReader
•
CharArrayWriter
The first two classes in this list work with files and the last four work inside Java, so they
aren't of great use for network programming. However, aside from different construc‐
tors, these classes have pretty much the same public interface as all other reader and
writer classes.
Writers
The
Writer
class mirrors the
java.io.OutputStream
class. It's abstract and has two
protected constructors. Like
OutputStream
, the
Writer
class is never used directly; in‐
stead, it is used polymorphically, through one of its subclasses. It has five
write()
methods as well as a
flush()
and a
close()
method:
protected
Writer
()
protected
Writer
(
Object
lock
)
public
abstract
void
write
(
char
[]
text
,
int
offset
,
int
length
)
throws
IOException
public
void
write
(
int
c
)
throws
IOException