Java StringReader

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 package.
  • It extends the abstract class Reader.
  • It implements Closeable, AutoCloseable and Readable 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 using the import statement. For creating the instance of StringReader, use one of its constructors.

In given below example, StringReader will read the characters from the string data.


//Create an instance in the application code
String data = "humpty dumpty";
StringReader stringReader = new StringReader(data);

3. Closing a StringReader

Calling the close() method on the StringReader closes the stream and releases any system resources associated with it.


Although if not closed, StringReader does not cause much trouble since it does not open any connection to a file or network socket.

4. Java StringReader Example

Lets see a few examples to read a file using the StringReader in Java.

Example 1: Read and print 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.


public class StringReaderExample 
	public static void main(String[] args) throws IOException 
		String data = "humpty dumpty";

		try (StringReader stringReader 
				= new StringReader(data)) 
			int ch =;
			while (ch != -1) 
				// do something with read char
				ch =;

Program output:

humpty dumpty

Example 2: Using StringReader in JAXB XML Parsing

In the given example, we want to parse a 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.

private Document parseXmlString(String xml) throws Exception  
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder documentBuilder = factory.newDocumentBuilder();

	InputSource inputSource = new InputSource(new StringReader(xml));
	return documentBuilder.parse(inputSource);

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.