THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

for (int i = 0; i < objs.length; i++)
out.println(i + ": " + objs[i]);
return strOut.toString();
}


20.5.8. Print Streams


The Print streamsPrintStream and PrintWriterprovide methods that make it easy to write the
values of primitive types and objects to a stream, in a human-readable text formatas you have seen in many
examples. The Print streams provide print and println methods for the following types:


char int float Object boolean

char[] long double String

These methods are much more convenient than the raw stream write methods. For example, given a float
variable f and a PrintStream reference out, the call out.print(f) is equivalent to


out.write(String.valueOf(f).getBytes());


The println method appends a line separator after writing its argument to the streama simple println
with no parameters ends the current line. The line separator string is defined by the system property
line.separator and is not necessarily a single newline character (\n).


Each of the Print streams acts as a Filter stream, so you can filter data on its way downstream.


The PrintStream class acts on byte streams while the PrintWriter class acts on character streams.
Because printing is clearly character-related output, the PrintWriter class is the class you should use.
However, for historical reasons System.out and System.err are PrintStreams that use the default
character set encodingthese are the only PrintStream objects you should use. We describe only the
PrintWriter class, though PrintStream provides essentially the same interface.


PrintWriter has eight constructors.


publicPrintWriter(Writer out, boolean autoflush)

Creates a new PrintWriter that will write to the stream out. If
autoflush is true, println invokes flush. Otherwise, println
invocations are treated like any other method, and flush is not invoked.
Autoflush behavior cannot be changed after the stream is constructed.

publicPrintWriter(Writer out)

Equivalent to PrintWriter(out,false).

publicPrintWriter(OutputStream out, boolean autoflush)

Equivalent to PrintWriter(new OutputStreamWriter(out),
autoflush).
Free download pdf