Java IO: CharArrayReader
Jakob Jenkov |
The Java CharArrayReader class (java.io.CharArrayReader) enables you to read the
contents of a char array as a character stream.
The Java CharArrayReader is handy when you have data in a char array, but need to
pass that data to some component which can only read from a Reader (or a Reader subclass).
Simply wrap the char array in a CharArrayReader and pass it to that component.
CharArrayReader Example
Here is a simple Java CharArrayReader example:
char[] chars = "123".toCharArray();
CharArrayReader charArrayReader =
new CharArrayReader(chars);
int data = charArrayReader.read();
while(data != -1) {
//do something with data
data = charArrayReader.read();
}
charArrayReader.close();
This example first creates a char array from a Java string. Second, the example creates
a CharArrayReader instance, passing the char array as parameter to the
CharArrayReader constructor. Third, the example reads the chars one by one from the
CharArrayReader, and finally the CharArrayReader is closed.
Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.
Creating a CharArrayReader From Part of a char Array
It is possible to create a Java CharArrayReader from just part of a char array.
Here is an example showing how to create a CharArrayReader that reads only part of a char
array:
char[] chars = "0123456789".toCharArray();
int offset = 2;
int length = 6;
CharArrayReader charArrayReader =
new CharArrayReader(chars, offset, length);
This example creates a CharArrayReader which only reads from the char with index 2
and 6 char elements forward in the char array.
Closing a CharArrayReader
Closing a CharArrayReader can be done using the close() method like this:
charArrayReader.close();
Or you can close the CharArrayReader using the Java 7
try-with-resources construct. Here is how that looks:
try(CharArrayReader charArrayReader =
new CharArrayReader(chars, offset, length)){
int data = charArrayReader.read();
while(data != -1) {
//do something with data
data = charArrayReader.read();
}
}
Notice that there is no explicit close() call on the CharArrayReader.
The try block takes care of that.
However, since the CharArrayReader is not using any underlying system resources like files or network
sockets, closing the CharArrayReader is not crucial.
| Tweet | |
Jakob Jenkov | |











