You use a reader almost exactly as you use an input stream. Rather
than reading bytes, you read characters. The basic
read()
method reads a specified number of
characters from the underlying input stream into an array starting at
a given offset:
public abstract int read(char[] buffer, int offset, int length) throws IOException
This read()
method returns the number of
characters actually read. As with input streams reading bytes, there
may not be as many characters available as you requested. Also like
the read()
method of an input stream, it returns
-1 when it detects the end of the data.
This read()
method is abstract. Concrete
subclasses that read bytes from some source must override this
method. An IOException
may be thrown if the
underlying stream’s read()
method throws an
IOException
or an encoding error is detected.
You can also fill an array with characters using this method:
public int read(char[] buffer) throws IOException
This is equivalent to invoking read(buffer,
0,
buffer.length)
. Thus, it
also returns the number of characters read and throws an
IOException
when the underlying stream throws an
IOException
or when an encoding error is detected.
The following method reads a single character and returns it:
public int read() throws IOException
Although an int
is returned, this
int
is always between
and 65,535 and may be cast to a char
without
losing information. All three read()
methods block
until some input is available, an I/O error occurs, or the end of the
stream is reached.
You can skip a certain number of characters. This method also blocks until some characters are available. It returns the number of characters skipped or -1 if the end of stream is reached.
public long skip(long n) throws IOException
The ready()
method returns true
if the reader is ready to be read from, false
if
it isn’t. Generally, this means the underlying stream has
available data.
public boolean ready() throws IOException
This is not quite the same as InputStream
’s
available()
method. available()
returns an int
specifying how many bytes are
available to be read. However, it’s not always possible to tell
how many characters are available in a stream without actually
reading them, particularly with encodings that use characters of
different widths (such as UTF-8, where a character may be one, two,
or three bytes).
Readers may or may not support marking and resetting, like input
streams. The markSupported()
method returns
true
if the underlying stream supports marking and
resetting, false
if it doesn’t.
public boolean markSupported() public void mark(int readAheadLimit) throws IOException public void reset() throws IOException
The close()
method closes the reader and its
underlying input stream and releases any resources the reader held:
public abstract void close() throws IOException
18.222.196.175