00:00

StringReader Class in Java: Reading Text from a String

Last updated:

Many APIs read text from a Reader. When the text is already in a String, such as a template, a test value or a response body, StringReader lets you pass it to that code without creating a file.

This tutorial covers the class and two practical examples.

1. What Is StringReader in Java?

StringReader extends Reader and reads characters from a String. No charset is involved, because the text is already made of characters. It was added in Java 1.1.

2. StringReader Class Hierarchy

StringReader class hierarchyStringReader extends the abstract class Reader, which extends Object, and implements Readable, Closeable and AutoCloseable. It reads characters from a String and is typically used for parsing text in memory, unit tests for code that uses Reader, and as the source of a BufferedReader.ObjectextendsReaderabstract classextendsStringReaderreads characters from a StringReadableCloseableAutoCloseableimplementsTypical usesparsing text in memoryunit tests for Reader codefeeding BufferedReader

Swipe sideways to see the whole diagram.

3. Constructor of StringReader

Constructor
public StringReader(String s)

4. Commonly Used Methods

MethodDescription
int read()Next character, or -1 at the end of the string.
int read(char[] cbuf, int off, int len)Copies characters into an array.
long skip(long n)Skips characters.
boolean ready()Always ready while the reader is open.
mark(int) / reset()Supported; markSupported() returns true.
void close()Closes the reader; later reads throw IOException.

5. Example: Finding Placeholders in a Template

An email service checks which placeholders a message template uses before filling them in.

PlaceholderFinder.java
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public class PlaceholderFinder {
    public static void main(String[] args) throws IOException {
        String template = "Hi {name}, your order {orderId} ships on {date}.";
        List<String> found = new ArrayList<>();

        try (StringReader in = new StringReader(template)) {
            StringBuilder current = null;
            int c;
            while ((c = in.read()) != -1) {
                if (c == '{') {
                    current = new StringBuilder();            // start of a placeholder
                } else if (c == '}' && current != null) {
                    found.add(current.toString());            // end of a placeholder
                    current = null;
                } else if (current != null) {
                    current.append((char) c);
                }
            }
        }
        System.out.println("Placeholders: " + found);
    }
}
Output
Placeholders: [name, orderId, date]

How the code works

  1. read() returns the template one character at a time.
  2. { starts collecting a name, and } stores it.
  3. The same logic could read a template file, because it only needs a Reader.

6. Example: Reading a Text Block Line by Line

A delivery app splits a multi-line address into lines for a shipping label. Wrapping a StringReader in a BufferedReader provides readLine().

AddressParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class AddressParser {
    public static void main(String[] args) throws IOException {
        String address = """
                Flat 12B, Lakeview Towers
                MG Road
                Bengaluru 560001
                India
                """;                                          // text block (Java 15)

        try (BufferedReader lines = new BufferedReader(new StringReader(address))) {
            String line;
            int number = 1;
            while ((line = lines.readLine()) != null) {
                System.out.println("Line " + number++ + ": " + line);
            }
        }
    }
}
Output
Line 1: Flat 12B, Lakeview Towers
Line 2: MG Road
Line 3: Bengaluru 560001
Line 4: India

How the code works

  1. The address is written as a text block (Java 15), which keeps its line breaks.
  2. BufferedReader reads the StringReader line by line.
  3. For simple cases, String.lines() (Java 11) does the same without a reader.

7. Common Mistakes and Best Practices

  • Using StringReader where a String method is enough. Use split() or lines() for simple tasks.
  • Reading after close(). It throws IOException.
  • Converting the string to bytes first. No charset is needed; read the characters directly.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1StringReader introduced.
Java 15Text blocks make multi-line strings easy to write.
Java 24Reader.of(CharSequence) also reads a String, StringBuilder or other sequence; standard in Java 25.

9. Summary

  • StringReader reads characters from a String.
  • It lets you pass in-memory text to code that expects a Reader.
  • Wrap it in a BufferedReader for readLine().
  • Since Java 24, Reader.of() is a flexible alternative.

Related Tutorials

10. Official Java Documentation References