Home  >  Core Java

Java CharArrayReader and CharArrayWriter Example

By Arvind Rai, June 13, 2014
In this page, we will see the example of Java CharArrayReader and CharArrayWriter. java.io. CharArrayReader and java.io. CharArrayWriter works on character array. CharArrayReader reads character array to display it as string where as CharArrayWriter writes character array data in a file.

Example of Java CharArrayReader

In the example, I have taken a character array. Now I will read this array using CharArrayReader.
CharArrayReaderDemo.java
package com.cp.io;
import java.io.CharArrayReader;
import java.io.IOException;
public class CharArrayReaderDemo {
	public static void main(String args[]) throws IOException { 
		char c[] = {'H','e','l','l','o',' ','W','o','r','l','d','!'}; 
		CharArrayReader chARedOne = new CharArrayReader(c); 
		CharArrayReader chARedTwo = new CharArrayReader(c, 0, 5); 
		int i; 
		while((i = chARedOne.read()) != -1) { 
			System.out.print((char)i); 
		} 
		System.out.println(); 
		while((i = chARedTwo.read()) != -1) { 
		    System.out.print((char)i); 
		} 
	} 
} 
Output will be
Hello World!
Hello
 

Example of Java CharArrayReader

CharArrayWriter writes char array data in file using FileWriter. CharArrayWriter writes multiple files after taking data in a buffer. In the example, I have a char array. I will write this char array data in a file as a string.
CharArrayWriterDemo.java
package com.cp.io;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CharArrayWriterDemo {
	public static void main(String args[]) throws IOException { 
		char c[] = {'H','e','l','l','o',' ','W','o','r','l','d','!'}; 
		CharArrayWriter out = new CharArrayWriter(); 
		out.write(c);
		FileWriter f1 = new FileWriter(new File("D:/cp/a.txt"));
		out.writeTo(f1); //File written successfully.
		
		FileWriter f2 = new FileWriter(new File("D:/cp/b.txt"));
		out.writeTo(f2); //File written successfully.
		
		f1.close();
		f2.close();
		
		//CharArrayWriter is closed.
		out.close();

		FileWriter f3 = new FileWriter(new File("D:/cp/c.txt"));
		//Write again to a file. No Exception from CharArrayWriter but no data will be written.
		out.writeTo(f3);
		
		System.out.println("Done");
	} 
} 
CharArrayWriter does not throw IO Exception if we access it after closing.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us