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:

CharArrayReader(char array[ ])
array is the input source.
CharArrayReader(char array[ ], int start, int numChars)
creates a Reader from a subset of the character array
void close()
Closes the stream and releases any system resources associated with it.
void mark(int readAheadLimit)
Marks the present position in the stream.
boolean markSupported()
Tells whether this stream supports the mark() operation, which it does.
int read()
Reads a single character.
int read(char[] b, int off, int len)
Reads characters into a portion of an array.
boolean ready()
Tells whether this stream is ready to be read.
void reset()
Resets the stream to the most recent mark, or to the beginning if it has never been marked.
long skip(long n)
Skips characters.

Revised from Open JDK source code

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

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);
  }
}
  

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

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
Home 
  Java Book 
    File Stream  

CharArrayReader:
  1. CharArrayReader
  2. new CharArrayReader(char[] buf, int offset, int length)