CharArrayWriter is a class in Java that extends the Writer abstract class and provides a buffer to write characters into an internal buffer which can later be used to create a String.
Here's an example program that uses CharArrayWriter:
import java.io.CharArrayWriter;
import java.io.IOException;
public class CharArrayWriterExample {
public static void main(String[] args) throws IOException {
CharArrayWriter writer = new CharArrayWriter();
String message = "Hello World!";
writer.write(message);
char[] buffer = writer.toCharArray();
System.out.println(new String(buffer));
writer.close();
}
}
The above program creates an instance of CharArrayWriter, writes the string "Hello World!" to it, and then converts the written characters into a character array using the toCharArray() method. Finally, the character array is printed as a String.
CharArrayWriter has two constructors:
CharArrayWriter(): Creates a newCharArrayWriterwith a default initial size of 32 characters.CharArrayWriter(int initialSize): Creates a newCharArrayWriterwith an initial buffer size ofinitialSize.