StringReader StringWriter Memory Text
StringWriter accumulates formatted text in memory and StringReader feeds it back through any Reader-based API, no temp files involved.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.