CharArrayWriter Java


Like StringWriter stores data in a StringBuffer, the CharArrayWriter stores data in a character array. The array size increases implicitly when more data is added. The data stored with CharArrayWriter object can be obtained using toString() or toCharArray() methods. The ealier closing of CharArrayWriter object does not have any affect on the data it stored.

Following is the class signature of CharArrayWriter Java

public class CharArrayWriter extends Writer

Writing and Extracting from CharacterArrayWriter Java

Following program writes and extracts strings from CharArrayWriter Java.

import java.io.*;
public class CAWDemo
{
  public static void main(String args[]) throws IOException
  {
    CharArrayWriter cawriter = new CharArrayWriter();
    cawriter.write("Greets");
    cawriter.write(85);
    cawriter.write('L');

    cawriter.close();   // ealier closing of stream

    System.out.println(cawriter);

    char carray[] = cawriter.toCharArray();
    String s1 = new String(carray, 0, carray.length);  
    System.out.println(s1);
  }
}

CharArrayWriter Java

Using write() method of CharArrayWriter, a string, an integer and a character are written. The integer value 85 is treated as ASCII value and when printed, it is converted to letter U.

System.out.println(cawriter);

The above statement can be modified as following using toString() method.

String s2 = cawriter.toString();
System.out.println(s2);

Pass your comments and suggestions on this tutorial "CharArrayWriter Java" to improve the quality further.

Leave a Comment

Your email address will not be published.