The CharArrayWriter class creates a character buffer in memory and all the character sent to one or more file is stored in the buffer. The buffer of CharArrayWriter automatically grows according to data. In this stream, the data is written into a character array. This class inherits Writer class. CharArrayWriter also has a close( ) method. But calling the close( ) method has no effect on the CharArrayWriter.

CharArrayWriter Constructors

Constructors Description
CharArrayWriter() Creates a new CharArrayWriter.
CharArrayWriter(int initialSize) Creates a new CharArrayWriter with the specified initial size.

CharArrayWriter Methods

Method Description
void write(int c) Writes a character(int to char) to the buffer.
void write(char[] c) Writes an array of characters to the buffer.
void write(char[] c, int off, int len) Writes a portion of an array of characters to the buffer.
void write(String str) Write a string to the buffer.
void write(String str, int off, int len) Write a portion of a string to the buffer.
void writeTo(Writer out) Writes the contents of the buffer to another character stream.
CharArrayWriter append(char c) Appends the specified character to this writer.
CharArrayWriter append(CharSequence csq) Appends the specified character sequence to this writer.
CharArrayWriter append(CharSequence csq, int start, int end) Appends a subsequence of the specified character sequence to this writer.
int         size() Returns the current size of the buffer.
void      reset() Resets the buffer so that you can use it again without throwing away the already allocated buffer.
char[]    toCharArray() Returns a copy of the input data.
String   toString() Converts input data to a string.
void      close() Invoking this method in this class will have no effect.



Program Source


public class Javaapp {
    public static void main(String[] args) throws IOException {
        CharArrayWriter cw = new CharArrayWriter(8);
        cw.write(new char[]{'s','o','f'});
        System.out.println("Valid chars : "+cw.size());
        try(FileWriter fw = new FileWriter("char.txt")){
        System.out.println("Valid chars : "+cw.size());

Leave a Comment