In this tutorial we will learn about the CharArrayWriter in Java.
java.io.CharArrayWriter extends the java.io.Writer. The CharArrayWriter class writes a character buffer to the output stream. This class is acted as a Writer to write the stream. toCharArray() and toString() methods can be used to get the data. close() method of this class has no effect.
Constructor Detail
| CharArrayWriter() | This default constructor is used to create a new CharArrayWriter. Syntax : public CharArrayWriter() |
| CharArrayWriter(int initialSize) | This constructor is used to create a new CharArrayWriter with the given
initial size. Syntax : public CharArrayWriter(int initialSize) |
Method Detail
Example
This example is being given here for demonstrating how to use CharArrayWriter. This example explains that how to write char array to the output stream using, read the characters, and write the data to the file. For this in the example I have used the methods of CharArrayWriter such as write() method (for writing to the output stream), toCharArray() (for reading the char array data), writeTo() (for writing the data to another Writer).
Source Code
import java.io.CharArrayWriter;
import java.io.FileWriter;
import java.io.IOException;
public class JavaCharArrayWriterExample
{
public static void main(String args[])
{
char ch[] = {'a', 'b', 'c', 'd'};
CharArrayWriter caw = null;
FileWriter fw = null;
try
{
caw = new CharArrayWriter();
System.out.println();
System.out.println("*****Output*****");
System.out.println("An array of character is written successfully to the output stream");
caw.write(ch);
char c[] = caw.toCharArray();
System.out.print("Data read through toCharArray is : ");
for(int i =0; i<c.length; i++)
{
System.out.print(c[i]);
}
System.out.println();
fw = new FileWriter("test.txt");
caw.writeTo(fw);
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if(caw != null)
{
try
{
caw.close();
fw.close();
}
catch(Exception ioe)
{
System.out.println(ioe);
}
}
}// end finally
}// end main
}// end class
Output
When you will execute the above example you will get the output as below as well as you will see that a file with the name which you have specified at the time of programming is created in the specified directory.

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java IO CharArrayWriter
Post your Comment