Java StringReader class is used to read character data from a string as a character stream.
In this chapter, we will learn what the StringReader class is, why it is used, its declaration, constructors, methods, and examples to understand how strings can be processed as character streams.
The StringReader class is a character stream that takes a String as its source and converts it into a readable character stream. It extends the Reader class and allows programs to read characters from a string just like reading from a file or other input stream.
The StringReader class works completely in memory. It does not use system resources such as files or network sockets, so calling the close() method on a StringReader object has no effect.
The StringReader class is a part of the java.io package and extends the Reader class.
The StringReader class provides a constructor to create a character input stream using a string.
This constructor creates a new StringReader using the specified string as the source of characters.
Syntax:
It has the following syntax:
The following example demonstrates how to create a StringReader object using a string.
The StringReader class provides methods to read characters, skip characters, and manage the reader.
| Method | Description |
|---|---|
| int read() | It is used to read a single character. |
| int read(char[] cbuf, int off, int len) | It is used to read a character into a portion of an array. |
| boolean ready() | It is used to tell whether the stream is ready to be read. |
| boolean markSupported() | It is used to tell whether the stream support mark() operation. |
| long skip(long ns) | It is used to skip the specified number of character in a stream |
| void mark(int readAheadLimit) | It is used to mark the mark the present position in a stream. |
| void reset() | It is used to reset the stream. |
| void close() | It is used to close the stream. |
Practice the following examples to understand the concept and usages of StringReader class.
The following example demonstrates how to read characters from a string using the StringReader class.
Output:
Hello Java!! Welcome to TpointTech.
The following example demonstrates how to read string data into a character array using StringReader.
Output:
Java I/O StringReader
We request you to subscribe our newsletter for upcoming updates.