Java Reference
In-Depth Information
Note that the
PrintWriter
class has no particular relevance to printing, in spite of its name. The
PrintWriter
class defines methods for formatting binary data as characters, and writing it to a stream.
It defines overloaded
print()
and
println()
methods that accept an argument of each of the basic
data types, of type
char[]
, of type
String
, and of type
Object
. The data that is written is a character
representation of the argument. Numerical values and objects are converted to a string representation
using the static
valueOf()
method in the
String
class. There are overloaded versions of this method
for all of the primitive types plus type Object. In the case of an argument that is an
Object
reference,
the
valueOf()
method just calls the
toString()
method for the object to produce the string to be
written to the stream. The
print()
methods just write the string representation of the argument
whereas the
println()
method appends
\n
to the output. You can create a
PrintWriter
object
from a stream or from another
Writer
object.
An important point to note when using a
PrintWriter
object is that its methods do not throw I/O
exceptions. To determine whether any I/O errors have occurred, you have to call the
checkError()
method for the
PrintWriter
object. This method will return
true
if an error occurred and
false
otherwise.
The
StringWriter
and
CharArrayWriter
classes are for writing character data to a
StringBuffer
object, or an array of type
char[]
. You would typically use these to perform data
conversions so that the results are available to you from the underlying array, or string. For instance,
you could combine the capabilities of a
PrintWriter
with a
StringWriter
to obtain a
String
object containing binary data converted to characters:
StringWriter strWriter = new StringWriter();
PrintWriter writer = new PrintWriter(strWriter);
Now you can use the methods for the
writer
object to write to the
StringBuffer
object underlying
the
StringWriter
object:
double value = 2.71828;
writer.println(value);
You can get the result back as a
StringBuffer
object from the original
StringWriter
object:
StringBuffer str = strWriter.getBuffer();
Of course, the formatting done by a
PrintWriter
object does not help make the output line up in
neat columns. If you want that to happen, you have to do it yourself. We'll take a look at how we might
do this for command line output a little later in this chapter.
Let's now turn to keyboard input and command line output.