The CharArrayWriter class is utilized for writing shared data to various files. This class is a subclass of the Writer class. The buffer of this class expands automatically as data is being written into the stream. Invoking the close function on this instance does not produce any impact.
Java CharArrayWriter class declaration
Let's examine the declaration of the Java.io.CharArrayWriter class:
Example
public class CharArrayWriter extends Writer
Java CharArrayWriter class Methods
| Method | Description |
|---|---|
| int size() | It is used to return the current size of the buffer. |
| char[] toCharArray() | It is used to return the copy of an input data. |
| String toString() | It is used for converting an input data to astring. |
| CharArrayWriter append(char c) | It is used to append the specified character to the writer. |
| CharArrayWriter append(CharSequence csq) | It is used to append the specified character sequence to the writer. |
| CharArrayWriter append(CharSequence csq, int start, int end) | It is used to append the subsequence of a specified character to the writer. |
| void write(int c) | It is used to write a character to the buffer. |
| void write(char[] c, int off, int len) | It is used to write a character to the buffer. |
| void write(String str, int off, int len) | It is used to write a portion of string to the buffer. |
| void writeTo(Writer out) | It is used to write the content of buffer to different character stream. |
| void flush() | It is used to flush the stream. |
| void reset() | It is used to reset the buffer. |
| void close() | It is used to close the stream. |
Example of CharArrayWriter Class:
In this instance, we are storing a shared dataset in four separate files named a.txt, b.txt, c.txt, and d.txt.
Example
package com.example;
import java.io.CharArrayWriter;
import java.io.FileWriter;
public class CharArrayWriterExample {
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("Welcome to Java");
FileWriter f1=new FileWriter("D:\\a.txt");
FileWriter f2=new FileWriter("D:\\b.txt");
FileWriter f3=new FileWriter("D:\\c.txt");
FileWriter f4=new FileWriter("D:\\d.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
System.out.println("Success...");
}
}
Output
Output
Success...
Upon running the program, it will become apparent that all files contain the shared information: "Welcome to Java."
a.txt:
Example
Welcome to Java
b.txt:
Example
Welcome to Java
c.txt:
Example
Welcome to Java
d.txt:
Example
Welcome to Java