The CharArrayReader class in Java is used to read a character array as a character input stream.
In this chapter, we will learn what the CharArrayReader class is, why it is used, its declaration, constructors, important methods, and how to read character arrays using examples.
The CharArrayReader class allows a character array to be treated as a character input stream. This means data stored in a character array can be read sequentially just like reading data from a file or any other reader.
It extends the Reader class and is mainly used when character data is already available in memory and needs to be processed using stream-based APIs.
The following declaration shows how the CharArrayReader class is defined:
The CharArrayReader class provides constructors to create a reader from a character array.
This constructor creates a reader that uses the given character array as its input source.
Syntax:
Here is the syntax:
This constructor creates a reader that reads a specified portion of the character array.
Syntax:
Here is the syntax:
The following code shows how the constructors of the CharArrayReader class are used.
The CharArrayReader class provides methods to read character data from the array.
| Method | Description |
|---|---|
| int read() | It is used to read a single character |
| int read(char[] b, int off, int len) | It is used to read characters into the portion of an array. |
| boolean ready() | It is used to tell whether the stream is ready to read. |
| boolean markSupported() | It is used to tell whether the stream supports mark() operation. |
| long skip(long n) | It is used to skip the character in the input stream. |
| void mark(int readAheadLimit) | It is used to mark the present position in the stream. |
| void reset() | It is used to reset the stream to a most recent mark. |
| void close() | It is used to closes the stream. |
The following examples demonstrate how to read character data using the Java CharArrayReader class.
The following example demonstrates how to read characters sequentially from a character array using the CharArrayReader class.
Output:
j : 106 a : 97 v : 118 a : 97 t : 116 p : 112 o : 111 i : 105 n : 110 t : 116
The following example demonstrates how to read only a specific portion of a character array using the CharArrayReader class.
Output:
Java
We request you to subscribe our newsletter for upcoming updates.