StringReader StringWriter Memory Text

StringWriter accumulates formatted text in memory and StringReader feeds it back through any Reader-based API, no temp files involved.

JavaCli Tooling

Code

snippet
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

public class MemoryText {

    public static void main(String[] args) throws IOException {
        // StringWriter accumulates written text in an in-memory buffer; toString grabs it anytime
        StringWriter out = new StringWriter();
        out.write("deploy notes");
        out.append(": phase ");
        out.write(String.valueOf(2));
        String report = out.toString();
        System.out.println("report: " + report);

        // StringReader lets Reader-based APIs consume an in-memory string
        try (StringReader in = new StringReader(report)) {
            char[] buffer = new char[8];
            int first = in.read(buffer);
            System.out.println("first chunk: " + new String(buffer, 0, first));
            int rest = in.read(buffer);
            System.out.println("second chunk: " + new String(buffer, 0, rest));
            System.out.println("next char code: " + in.read());
        }
    }
}

What the demo buffers

StringWriter collects whatever is written — write, append and a String.valueOf round-trip — into one growing buffer, and toString hands back the assembled report: deploy notes: phase 2. No file is touched at any point.

StringReader then feeds that same string into the classic Reader API surface: an 8-char buffer read returns deploy n, the next read returns otes: ph, and the final read() prints the remaining character code. Every call behaves exactly as it would against a file.

Practical notes

  • try-with-resources closes the StringReader like any Reader.
  • Chunk sizes come from the caller; the reader just supplies characters.

Interactive Tools for This Topic

FAQ

Why use StringReader instead of the string directly?
APIs typed to accept Reader, such as parsers and template filters, work unchanged; the demo drives the string through chunked read calls with no temp file involved.