StringWriter Class in Java: Writing Text to a String
Some APIs only write their output to a Writer, such as printStackTrace(), template engines and XML or JSON libraries. When you need that output as a String, StringWriter collects it in memory.
This tutorial covers the class and two practical examples.
1. What Is StringWriter in Java?
StringWriter extends Writer and stores everything written to it in an internal StringBuffer. Call toString() to get the text. It was added in Java 1.1.
2. StringWriter Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of StringWriter
| Constructor | Description |
|---|---|
StringWriter() | Starts with the default buffer size. |
StringWriter(int initialSize) | Starts with room for initialSize characters. |
4. Commonly Used Methods
| Method | Description |
|---|---|
write(String str) / write(int c) | Adds text; these methods do not throw IOException. |
StringWriter append(CharSequence csq) | Adds text and returns the same writer for chaining (Java 5). |
String toString() | The text written so far. |
StringBuffer getBuffer() | The internal buffer itself. |
flush() / close() | Do nothing useful; closing has no effect. |
5. Example: Turning a Stack Trace into a String
An error-reporting service sends exception details by email, so it needs the stack trace as a String.
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
static void chargeCard(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive: " + amount);
}
}
public static void main(String[] args) {
try {
chargeCard(-50);
} catch (IllegalArgumentException e) {
StringWriter trace = new StringWriter();
e.printStackTrace(new PrintWriter(trace)); // the trace goes into the StringWriter
String text = trace.toString();
System.out.println("First line: " + text.lines().findFirst().orElse(""));
System.out.println("Mentions chargeCard: " + text.contains("chargeCard"));
}
}
}
First line: java.lang.IllegalArgumentException: Amount must be positive: -50 Mentions chargeCard: true
How the code works
printStackTrace(PrintWriter)writes the trace to any writer; here aPrintWriterwraps theStringWriter.toString()returns the full trace, which can be logged, emailed or stored.lines().findFirst()(Java 11) shows the first line, the exception type and message.
6. Example: Building JSON Text
A job portal builds a small JSON profile by appending pieces of text.
import java.io.StringWriter;
public class JsonBuilder {
public static void main(String[] args) {
String[] skills = {"Java", "Spring", "SQL"};
StringWriter json = new StringWriter();
json.append("{\"name\":\"Ananya\",") // append() returns the writer, so calls chain
.append("\"experience\":4,")
.append("\"skills\":[");
for (int i = 0; i < skills.length; i++) {
if (i > 0) json.append(',');
json.append('"').append(skills[i]).append('"');
}
json.append("]}");
System.out.println(json);
System.out.println("Length: " + json.getBuffer().length());
}
}
{"name":"Ananya","experience":4,"skills":["Java","Spring","SQL"]}
Length: 65
How the code works
append()returns theStringWriter, so calls can be chained.append(char)adds single characters such as commas and quotes.getBuffer().length()returns the number of characters written.
For real applications, use a JSON library, which handles escaping correctly.
7. StringWriter vs StringBuilder
| Aspect | StringWriter | StringBuilder |
|---|---|---|
| Type | A Writer | A mutable character sequence |
| Use it when | An API needs a Writer | You build text yourself |
| Thread safety | Uses a synchronized StringBuffer internally | Not synchronized, slightly faster |
8. Common Mistakes and Best Practices
- Using
StringWriterto concatenate strings in your own code. AStringBuilderis simpler. - Building JSON or HTML by hand. Use a library that escapes special characters.
- Collecting huge outputs in memory. Write large output directly to a file.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.1 | StringWriter introduced. |
| Java 5 | append() methods. |
| Java 11 | String.lines(), used to read the trace. |
| Java 25 | No API changes. |
10. Summary
StringWritercollects written characters in memory.- Use it when an API writes to a
Writerbut you need aString. - Combine it with
PrintWriterto capture stack traces. - Closing it has no effect.
Related Tutorials
- StringReader Class in Java
- PrintWriter Class in Java
- Writer Class in Java
- ByteArrayOutputStream Class in Java