O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 chars. 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 chars 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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required