Character Array Readers and Writers
The java.io.ByteArrayInputStream
and
java.io.ByteArrayOutputStream
classes let
programmers use stream methods to read and write arrays of bytes. The
java.io.CharArrayReader
and
java.io.CharArrayWriter
classes allow programmers
to use Reader
and Writer
methods to read and write arrays of char
s. Since
char
arrays are purely internal to Java and thus
composed of true Unicode characters, this is one of the few uses of
readers and writers where you don’t need to concern yourself
with conversions between different encodings. If you want to read
arrays of text encoded in some non-Unicode encoding, you should chain
a ByteArrayInputStream
to an
InputStreamReader
instead. Similarly, to write
text into a byte array in a non-Unicode encoding, just chain an
OutputStreamWriter
to a
ByteArrayOutputStream
.
The CharArrayWriter Class
The CharArrayWriter
maintains an internal array of
char
s into which successive characters are
written. The array is expanded as needed. This array is stored in a
protected field called buf
:
protected char[] buf
For efficiency, the array generally contains more components than
characters. The number of characters actually written is stored in a
protected int
field called
count
:
protected int count
The value of the count
field is always less than
or equal to buf.length
.
The no-argument constructor creates a
CharArrayWriter
object with a 32-character buffer.
This is on the small side, so you can expand it with the second
constructor:
public CharArrayWriter() ...
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.