Java Reference
In-Depth Information
public
boolean
markSupported
()
public
void
mark
(
int
readAheadLimit
)
throws
IOException
public
void
reset
()
throws
IOException
public
abstract
void
close
()
throws
IOException
The
read(char[] text, int offset, int length)
method is the fundamental meth‐
od through which the other two
read()
methods are implemented. A subclass must
override at least this method as well as
close()
, although most will override some of
the other methods as well in order to provide more efficient implementations.
Most of these methods are easily understood by analogy with their
InputStream
coun‐
terparts. The
read()
method returns a single Unicode character as an
int
with a value
from 0 to 65,535 or -1 on end of stream. (Technically it returns a UTF-16 code point,
though almost always that's the same as a Unicode character.) The
read(char[]
text)
method tries to fill the array
text
with characters and returns the actual number
of characters read or -1 on end of stream. The
read(char[]
text, int
offset, int
length)
method attempts to read
length
characters into the subarray of
text
beginning
at
offset
and continuing for
length
characters. It also returns the actual number of
characters read or -1 on end of stream. The
skip(long
n)
method skips
n
characters.
The
mark()
and
reset()
methods allow some readers to reset back to a marked position
in the character sequence. The
markSupported()
method tells you whether the reader
supports marking and resetting. The
close()
method closes the reader and any un‐
derlying input stream so that further attempts to read from it throw
IOException
s.
The exception to the rule of similarity is
ready()
, which has the same general purpose
as
available()
but not quite the same semantics, even modulo the byte-to-char con‐
version. Whereas
available()
returns an
int
specifying a minimum number of bytes
that may be read without blocking,
ready()
only returns a
boolean
indicating whether
the reader may be read without blocking. The problem is that some character encodings,
such as UTF-8, use different numbers of bytes for different characters. Thus, it's hard
to tell how many characters are waiting in the network or filesystem buffer without
actually reading them out of the buffer.
InputStreamReader
is the most important concrete subclass of
Reader
. An
Input
StreamReader
reads bytes from an underlying input stream such as a
FileInput
Stream
or
TelnetInputStream
. It converts these into characters according to a specified
encoding and returns them. The constructor specifies the input stream to read from
and the encoding to use:
public
InputStreamReader
(
InputStream
in
)
public
InputStreamReader
(
InputStream
in
,
String
encoding
)
throws
UnsupportedEncodingException
If no encoding is specified, the default encoding for the platform is used. If an unknown
encoding is specified, an
UnsupportedEncodingException
is thrown.