Java - CharArrayReader and CharArrayWriter example

Posted on November 9, 2016


CharArrayReader class and CharArrayWriter class implement a character buffer that can be used as a character-input stream and character- output stream respectively. Invoking close() method of the CharArrayReader class and CharArrayWriter class have no effect.

Here is an example of CharArrayReader class.

CharArrayReaderExample.java

package com.boraji.tutorial.io;

import java.io.CharArrayReader;
import java.io.IOException;

/**
 * @author imssbora
 */
public class CharArrayReaderExample {
	public static void main(String[] args) {
		char ch[] = "This is an example of CharArrayReader.".toCharArray();
		CharArrayReader charArrayReader = null;
		try {
			charArrayReader = new CharArrayReader(ch);

			// Read characters
			int c;
			while ((c = charArrayReader.read()) != -1) {
				System.out.print((char) c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output

This is an example of CharArrayReader.

Following is an example of CharArrayWriter class.

CharArrayWriterExample.java

package com.boraji.tutorial.io;

import java.io.CharArrayWriter;
import java.io.IOException;

/**
 * @author imssbora
 */
public class CharArrayWriterExample {
	public static void main(String[] args) {
		CharArrayWriter charArrayWriter = new CharArrayWriter();

		try {
			// Write characters to Writer
			charArrayWriter.write("This is an example of CharArrayWriter");

			// Get character array from writer
			char[] ch = charArrayWriter.toCharArray();
			for (char c : ch) {
				System.out.print(c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

Output

This is an example of CharArrayWriter