00:00

StringWriter Class in Java: Writing Text to a String

Last updated:

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

StringWriter class hierarchyStringWriter extends the abstract class Writer, which extends Object, and implements Appendable, Closeable, Flushable and AutoCloseable. It collects characters in a buffer; the result is returned by toString or getBuffer, which returns a StringBuffer.ObjectextendsWriterabstract classextendsStringWritercollects characters in a bufferAppendableCloseableFlushableAutoCloseableimplementsGet the result withtoString()getBuffer() (a StringBuffer)

Swipe sideways to see the whole diagram.

3. Constructors of StringWriter

ConstructorDescription
StringWriter()Starts with the default buffer size.
StringWriter(int initialSize)Starts with room for initialSize characters.

4. Commonly Used Methods

MethodDescription
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.

StackTraceToString.java
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"));
        }
    }
}
Output
First line: java.lang.IllegalArgumentException: Amount must be positive: -50
Mentions chargeCard: true

How the code works

  1. printStackTrace(PrintWriter) writes the trace to any writer; here a PrintWriter wraps the StringWriter.
  2. toString() returns the full trace, which can be logged, emailed or stored.
  3. 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.

JsonBuilder.java
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());
    }
}
Output
{"name":"Ananya","experience":4,"skills":["Java","Spring","SQL"]}
Length: 65

How the code works

  1. append() returns the StringWriter, so calls can be chained.
  2. append(char) adds single characters such as commas and quotes.
  3. getBuffer().length() returns the number of characters written.

For real applications, use a JSON library, which handles escaping correctly.

7. StringWriter vs StringBuilder

AspectStringWriterStringBuilder
TypeA WriterA mutable character sequence
Use it whenAn API needs a WriterYou build text yourself
Thread safetyUses a synchronized StringBuffer internallyNot synchronized, slightly faster

8. Common Mistakes and Best Practices

  • Using StringWriter to concatenate strings in your own code. A StringBuilder is 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 versionChange
Java 1.1StringWriter introduced.
Java 5append() methods.
Java 11String.lines(), used to read the trace.
Java 25No API changes.

10. Summary

  • StringWriter collects written characters in memory.
  • Use it when an API writes to a Writer but you need a String.
  • Combine it with PrintWriter to capture stack traces.
  • Closing it has no effect.

Related Tutorials

11. Official Java Documentation References