Java IO: StringWriter

Jakob Jenkov
Last update: 2015-09-11

The Java StringWriter class (java.io.StringWriter) enables you to obtain the characters written to a Writer as a String. The StringWriter is useful if you have a component that only can write data to a Writer but you need that data as a String.

StringWriter Example

Here is a simple Java StringWriter example:

StringWriter stringWriter = new StringWriter();

//write characters to writer.
stringWriter.write("This is a text");

String       data       = stringWriter.toString();
StringBuffer dataBuffer = stringWriter.getBuffer();

stringWriter.close();

This example first creates a StringWriter. Second, the example writes a String to the StringWriter.

Third the characters written to the StringWriter are obtained via the two methods toString() and getBuffer(). You only need to use one of these two methods, but both are showed so you know they both exist.

The method toString() returns the characters written to the StringWriter as a String.

The method getBuffer() returns the StringBuffer used by the StringWriter to build the string from the written characters.

Closing a StringWriter

When you are finished writing characters to a Java StringWriter you can close. Since the StringWriter is not connected to any underlying system resources, like files or network connections, it is not crucial to close it.

Closing a StringWriter is done by calling its close() method. Here is how closing a Java StringWriter looks:

stringWriter.close();

You can also use the try-with-resources construct introduced in Java 7. Here is how to use and close a StringWriter looks with the try-with-resources construct:

try(StringWriter stringWriter =
    new StringWriter() ){

    stringWriter.write("data 1");
    stringWriter.write("data 2");
    stringWriter.write("data 3");

    String writtenText = stringWriter.toString();
}

Notice how there is no longer any explicit close() method call to the StringWriter instance. The try-with-resources construct takes care of that.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next