Read & Write file in java using CharArrayReader & CharArrayWriter (example)

  • Given the contents, we would like to create or write to file using CharArrayWriter class in java.
  • Read contents from file using CharArrayReader class.

1. CharArrayReader class:

  • CharArrayReader is used to read contents of file as character array.
  • CharArrayReader class has couple of constructors as follows.
No.Contructor Description
1CharArrayReader(char[] buf) Creates a CharArrayReader from the specified array of chars.
2CharArrayReader(char[] buf, int offset, int length) Creates a CharArrayReader from the specified array of chars.

2. CharArrayWriter class:

  • CharArrayWrite class is used to write contents as character(s) to the file.
  • CharArrayWriter class has following contructors.
No.Contructor Description
1CharArrayWriter() Creates a new CharArrayWriter.
2CharArrayWriter(int initialSize) Creates a new CharArrayWriter with the specified initial size.

3. Read & write file in java (CharArrayReader/ CharArrayWriter/ example)

package org.learn.io;

import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CharArrayReaderWriter {
	public static void main(String[] args) throws IOException {
		writeUsingCharArrayWriter();
		readUsingCharArrayReader();
	}

	private static void writeUsingCharArrayWriter() throws IOException {
		System.out.println("1. Writting contents to file using CharArrayWriter");
		String newLine = System.getProperty("line.separator");
		try (FileWriter fileWriter = new FileWriter(new File("sampleFile.txt"));
				CharArrayWriter charArrayWriter = new CharArrayWriter()) {
			charArrayWriter.write("Soccer");
			charArrayWriter.write(newLine);
			charArrayWriter.write("Tennis");
			charArrayWriter.write(newLine);
			charArrayWriter.write("Badminton");
			charArrayWriter.write(newLine);
			charArrayWriter.write("Hockey");
			charArrayWriter.write(newLine);
			charArrayWriter.writeTo(fileWriter);
		}
		System.out.println("2. Successfully writtent contents to file using CharArrayWriter");
	}

	private static void readUsingCharArrayReader() throws IOException {
		System.out.println("3. Reading contents using CharArrayReader");
		char[] buffer = "We have read this buffer using CharArrayReader.".toCharArray();
		CharArrayReader reader = new CharArrayReader(buffer);

		int ch;
		while ((ch = reader.read()) != -1) {
			System.out.printf("%c", (char) ch);
		}
		reader.close();
		System.out.println("\n4. Successfully read contents using CharArrayReader");
	}
}

4. Read & write file in java (CharArrayReader/ CharArrayWriter/ example)

1. Writting contents to file using CharArrayWriter
2. Successfully writtent contents to file using CharArrayWriter
3. Reading contents using CharArrayReader
We have read this buffer using CharArrayReader.
4. Successfully read contents using CharArrayReader
Scroll to Top