CharArrayWriter sample program in Java

By: Baski Printer Friendly Format    

CharArrayWriter is an implementation of an output stream that uses an array as the destination. CharArrayWriter has two constructors, shown here:

CharArrayWriter( )
CharArrayWriter(int numChars)

In the first form, a buffer with a default size is created. In the second, a buffer is created with a size equal to that specified by numChars. The buffer is held in the buf field of CharArrayWriter. The buffer size will be increased automatically, if needed. The number of characters held by the buffer is contained in the count field of CharArrayWriter. Both buf and count are protected fields.

The following example demonstrates CharArrayWriter by reworking the sample program shown earlier for ByteArrayOutputStream. It produces the same output as the previous version.

// Demonstrate CharArrayWriter.
class CharArrayWriterDemo {
public static void main(String args[]) throws IOException {
CharArrayWriter f = new CharArrayWriter();
String s = "This should end up in the array";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
System.out.println("Buffer as a string");
System.out.println("Into array");
char c[] = f.toCharArray();
for (int i=0; i<c.length; i++) {
System.out.println("\\nTo a FileWriter()");
FileWriter f2 = new FileWriter("test.txt");
System.out.println("Doing a reset");
for (int i=0; i<3; i++)

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial