CharArrayReader is a subclass of Reader that allows you to read character data from a character array. Here's an example program that demonstrates its usage:
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
public class CharArrayReaderExample {
public static void main(String[] args) {
char[] data = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
try (Reader reader = new CharArrayReader(data)) {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this program, we create a character array containing the text "hello world", and then pass that array to a new instance of CharArrayReader. We then use a while loop to read the characters from the reader one at a time and print them to the console. When the end of the reader is reached (which occurs when reader.read() returns -1), the loop exits and the try block completes, causing the reader to be automatically closed.