THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

20.5.7. String Character Streams


The StringReader reads its characters from a String and will never block. It provides a single
constructor that takes the string from which to read. For example, the following program factors numbers read
either from the command line or System.in:


class Factor {
public static void main(String[] args) {
if (args.length == 0) {
factorNumbers(new InputStreamReader(System.in));
} else {
for (String str : args) {
StringReader in = new StringReader(str);
factorNumbers(in);
}


}
}
// ... definition of factorNumbers ...
}


If the command is invoked without parameters, factorNumbers parses numbers from the standard input
stream. When the command line contains some arguments, a StringReader is created for each parameter,
and factorNumbers is invoked on each one. The parameter to factorNumbers is a stream of characters
containing numbers to be parsed; it does not know whether they come from the command line or from
standard input.


StringWriter lets you write results into a buffer that can be retrieved as a String or StringBuffer
object. It adds the following constructors and methods:


publicStringWriter()

Creates a new StringWriter with a default initial buffer size.

publicStringWriter(int size)

Creates a new StringWriter with the specified initial buffer size.
Providing a good initial size estimate for the buffer will improve performance
in many cases.

public StringBuffergetBuffer()

Returns the actual StringBuffer being used by this stream. Because the
actual StringBuffer is returned, you should take care not to modify it
while it is being used as an output destination.

public StringtoString()

Returns the current contents of the buffer as a String.

The following code uses a StringWriter to create a string that contains the output of a series of
println calls on the contents of an array:


public static String arrayToStr(Object[] objs) {
StringWriter strOut = new StringWriter();
PrintWriter out = new PrintWriter(strOut);

Free download pdf