Java StringReader
class represents a character stream whose source is a string. The main use of this class is to pass a String content to a method that accepts a parameter of Reader
Type.
1. StringReader class
- It is meant for reading streams of characters whose source is a string.
- It is part of
java.io
package. - It extends the abstract class
Reader
. - It implements
Closeable
,AutoCloseable
andReadable
interfaces. - It provides methods for reading the characters from the Stream.
2. Creating a StringReader
To use the StringReader
in the application, we must first import it from package java.io
using the import statement. For creating the instance of StringReader
, use one of its constructors.
In the given below example, StringReader
will read the characters from the string data
.
String data = "humpty dumpty";
StringReader stringReader = new StringReader(data);
3. Using StringReader
Let us see a few examples to read a file using the StringReader
in Java.
3.1. Reading the Characters of a String using StringReader
In the given example, we are reading the characters from the String data
. we then print the read characters into the standard output.
String data = "humpty dumpty";
try (StringReader stringReader
= new StringReader(data))
{
int ch = stringReader.read();
while (ch != -1)
{
ch = stringReader.read();\
//System.out.print((char)ch);
}
}
3.2 Using StringReader for Parsing XML
In the given example, we want to parse an XML string (generally obtained as API response) to JAXB Document
object. The parse()
method accepts the Reader
type, so we use StringReader
to wrap the String response and pass it to the parse()
method.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xml));
Document document = documentBuilder.parse(inputSource);
Happy Learning !!