Java Reference
In-Depth Information
Writing to the Command Line
Up to now, we have made extensive use of the println() method from the PrintStream class in
our examples to output formatted information to the screen. The out object in the expression,
System.out.println() , is of type, PrintStream . This class outputs data of any of the basic types
as a string. For example, an int value of 12345 becomes the string, "12345" , as generated by the
valueOf() method from the String class. However, we also have the PrintWriter class that we
discussed earlier to do the same thing since this class has all the methods that PrintStream provides.
The principle difference between the two classes is that with the PrintWriter class you can control
whether or not the stream buffer is flushed when the println() method is called, whereas with the
PrintStream class you cannot. The PrintWriter class will only flush the stream buffer when one of
the println() methods is called if automatic flushing is enabled. A PrintStream object will flush
the stream buffer whenever a newline character is written to the stream, regardless of whether it was
written by a print() or a println() method.
Both the PrintWriter and PrintStream classes format basic data as characters. The functionality
that is missing is the ability to specify a field width for each output value. However, it is quite easy to
line your numeric output up in columns by defining your own subclass of either PrintStream or
PrintWriter . The approach is similar with both so let's arbitrarily try the latter.
Try It Out - Creating a Formatted Output Class
There is more than one approach possible to producing output in a given field width. We will create a
FormattedWriter class that defines objects that can write values of any of the basic types to a stream,
with a given field width. The class will implement overloaded print() and println() methods for
each of the primitive types.
We will define the class with a data member containing the width of the output field for data items. The
basic class definition will be:
import java.io.*;
public class FormattedWriter extends PrintWriter {
public final static int LEFT _ JUSTIFIED = 1;
public final static int RIGHT _ JUSTIFIED = 2;
private int justification = RIGHT _ JUSTIFIED;
private int width = 0; // Field width required for output
// Constructor with a specified field width, autoflush, and justification
public FormattedWriter(Writer output, boolean autoflush, int width,
int justification) {
super(output, autoflush); // Call PrintWriter constructor
if(width>0)
this.width = width; // Store the field width
if(justification == LEFT _ JUSTIFIED || justification == RIGHT _ JUSTIFIED)
this.justification = justification;
}
// Constructor with a specified field width
Search WWH ::




Custom Search