CharArrayReader

In this chapter you will learn:

  1. What is CharArrayReader and how to use Java CharArrayReader
  2. Create CharArrayReader from char array and read
  3. Create a CharArrayReader from a sub char array

Use CharArrayReader

CharArrayReader is an input stream that uses a character array as the source.

This class has two constructors, each of which requires a character array to provide the data source:

import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
/*jav a  2 s  .c  om*/
public class Main {
  public static void main(String args[]) throws IOException {
    CharArrayWriter outStream = new CharArrayWriter();
    String s = "This is a test.";
    for (int i = 0; i < s.length(); ++i)
      outStream.write(s.charAt(i));
    System.out.println("outstream: " + outStream);
    System.out.println("size: " + outStream.size());
    CharArrayReader inStream;
    inStream = new CharArrayReader(outStream.toCharArray());
    int ch = 0;
    StringBuffer sb = new StringBuffer("");
    while ((ch = inStream.read()) != -1)
      sb.append((char) ch);
    s = sb.toString();
    System.out.println(s.length() + " characters were read");
    System.out.println("They are: " + s);
  }
}

Create from char array

The following code creates CharArrayReader and read character by character then append to a StringBuffer.

import java.io.CharArrayReader;
import java.io.IOException;
/*from   j av a2  s  . c  o m*/
public class Main {
  public static void main(String args[]) throws IOException {
    CharArrayReader inStream;
    inStream = new CharArrayReader(new char[] { 'j', 'a', 'v', 'a', '2', 's', '.', 'c', 'o', 'm' });
    int ch = 0;
    StringBuffer sb = new StringBuffer("");
    while ((ch = inStream.read()) != -1)
      sb.append((char) ch);
    String s = sb.toString();
    System.out.println(s.length() + " characters were read");
    System.out.println("They are: " + s);

  }
}

The output:

10 characters were read
They are: java2s.com

Create a CharArrayReader from a sub char array

If we just need part of a char array we can just create a CharArrayReader from a sub char array.

import java.io.CharArrayReader;
import java.io.IOException;
/*from  java2s.  c  om*/
public class Main {
  public static void main(String args[]) throws IOException {
    String tmp = "abcdefghijklmnopqrstuvwxyz";
    int length = tmp.length();
    char c[] = new char[length];

    tmp.getChars(0, length, c, 0);
    CharArrayReader input1 = new CharArrayReader(c);
    CharArrayReader input2 = new CharArrayReader(c, 0, 5);

    int i;
    while ((i = input1.read()) != -1) {
      System.out.print((char) i);
    }

    while ((i = input2.read()) != -1) {
      System.out.print((char) i);
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is StringReader and how to use Java StringReader