Java Reference
In-Depth Information
public abstract int read(char[] buf, int offset, int length) throws IOException;
This method is the reason the
Reader
class is abstract and has to be implemented in any concrete sub-
class. The method reads
length
characters into the
buf
array starting at position
buf[offset]
. The method
also returns the number of characters that were read or 21 if the end of the stream was reached.
Another
read()
method reads characters into a buffer:
public int read(CharBuffer buffer) throws IOException;
This reads characters into the
CharBuffer
buffer specified by the argument. No manipulation of the buf-
fer is performed. The method returns the number of characters transferred to
buffer
or 21 if the source of
characters is exhausted.
All four
read()
methods can throw an exception of type
IOException
, and the
read()
method declared
in
Readable
can also throw an exception of
NullPointerException
if the argument is
null
.
The
Writer
class implements the
Appendable
interface. This declares three versions of the
append()
method; one takes an argument of type
char
and appends the character that is passed to it to whatever stream
the
Writer
encapsulates, another accepts an argument of type
CharSequence
and appends that to the under-
lying stream, and the third appends a subsequence of a character sequence to the stream. Recall from Chapter
6 that a
CharSequence
reference can refer to an object of type
String
, an object of type
StringBuilder
,
an object of type
StringBuffer
, or an object of type
CharBuffer
, so the
append()
method handles any of
these. The
Writer
class has five
write()
methods (shown in
Table 8-4
)
, all of which have a
void
return
type and throw an
IOException
if an I/O error occurs.
DESCRIPTION
Writes the character corresponding to the low-order 2 bytes of the integer argument,
ch
.
write(int ch)
Writes the array of characters
buf.
write(char[]
buf)
This is an abstract method that writes
length
characters from
buf
starting at
buf[offset].
write(char[]
buf,
int offset,
int length)
Writes the string
str.
write(String
str)
Writes
length
characters from
str
starting with the character at index position
offset
in the
string.
write(String
str,
int offset,
int length)
The
Reader
and
Writer
classes and their subclasses are not really streams themselves, but provide the
methods you can use for reading and writing an underlying stream as a character stream. Thus, you typically
create a
Reader
or
Writer
object using an underlying
InputStream
or
OutputStream
object that encapsu-
lates the connection to the external device that is the ultimate source or destination of the data.
Using Readers