CharArrayWriter Class in java

In the previous post, we have seen BufferedInputStream and BufferedOutputStream. In this post, we will CharArrayWriter class.

This class writes characters to a writer and converts those written characters into a char arary.

CharArrayWriter writer = new CharArrayWriter();

//write characters to writer.

char[] chars = writer.toCharArray();

CharArrayWriter class can be used to write data to multiple files. Its buffer automatically grows when data is written in this stream. Using close() method has no effect on this.

Example of CharArrayWriter class:

public class FileHandlingEx {
	public static void main(String[] args){	
		try {
		  CharArrayWriter out=new CharArrayWriter();  
		  out.write("This is example of writing in multiple files");  
		  		
		  FileWriter fw1 = new FileWriter("Sample1.txt");
		  FileWriter fw2=new FileWriter("Sample2.txt");  
		  FileWriter fw3=new FileWriter("Sample3.txt");  
		  out.writeTo(fw1);  
		  out.writeTo(fw2);  
		  out.writeTo(fw3);  
		  		  
		  fw1.close();  
		  fw2.close();  
		  fw3.close();  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}	
}
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum

 

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 8, 2015

    […] the previous post, we have seen CharArrayWriter class. In this post, we will see the usage of Console […]