Java Reference
In-Depth Information
For example, this method reads an input stream and converts it all to one Unicode string
using the MacCyrillic encoding:
public
static
String
getMacCyrillicString
(
InputStream
in
)
throws
IOException
{
InputStreamReader
r
=
new
InputStreamReader
(
in
,
"MacCyrillic"
);
StringBuilder
sb
=
new
StringBuilder
();
int
c
;
while
((
c
=
r
.
read
())
!=
-
1
)
sb
.
append
((
char
)
c
);
return
sb
.
toString
();
}
Filter Readers and Writers
The
InputStreamReader
and
OutputStreamWriter
classes act as decorators on top of
input and output streams that change the interface from a byte-oriented interface to a
character-oriented interface. Once this is done, additional character-oriented filters can
be layered on top of the reader or writer using the
java.io.FilterReader
and
java.io.FilterWriter
classes. As with filter streams, there are a variety of subclasses
that perform specific filtering, including:
•
BufferedReader
•
BufferedWriter
•
LineNumberReader
•
PushbackReader
•
PrintWriter
The
BufferedReader
and
BufferedWriter
classes are the character-based equivalents
of the byte-oriented
BufferedInputStream
and
BufferedOutputStream
classes. Where
BufferedInputStream
and
BufferedOutputStream
use an internal array of bytes as a
buffer,
BufferedReader
and
BufferedWriter
use an internal array of chars.
When a program reads from a
BufferedReader
, text is taken from the buffer rather
than directly from the underlying input stream or other text source. When the buffer
empties, it is filled again with as much text as possible, even if not all of it is immediately
needed, making future reads much faster. When a program writes to a
BufferedWriter
, the text is placed in the buffer. The text is moved to the underlying
output stream or other target only when the buffer fills up or when the writer is explicitly
flushed, which can make writes much faster than would otherwise be the case.
BufferedReader
and
BufferedWriter
have the usual methods associated with readers
and writers, like
read()
,
ready()
,
write()
, and
close()
. They each have two con‐
structors that chain the
BufferedReader
or
BufferedWriter
to an underlying reader