O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

String Readers and Writers

The java.io.StringReader and java.io.StringWriter classes allow programmers to use Reader and Writer methods to read and write strings. Like char arrays, Java strings are also composed of pure Unicode characters. Therefore, they’re good sources of data for readers and good targets for writers. This is the other common case where readers and writers don’t need to convert between different encodings.

String Writers

This class would more accurately be called StringBufferWriter, but StringWriter is more poetic. A StringWriter maintains an internal java.lang.StringBuffer object to which written characters are appended. This buffer can easily be converted to a string as necessary.

public class StringWriter extends Writer

There is a single public constructor:

public StringWriter()

There is also a constructor that allows you to specify the initial size of the internal string buffer. This isn’t too important, because string buffers (and, by extension, string writers) are expanded as necessary. Still, if you can estimate the size of the string in advance, it’s marginally more efficient to select a size big enough to hold all characters that will be written. The constructor is protected in Java 1.1 and public in Java 2:

protected StringWriter(int initialSize)
public StringWriter(int initialSize)  // Java 2

The StringWriter class has the usual collection of write() methods, all of which just append their data to the StringBuffer:

public void write(int c) public void write(char[] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required