The program PrintWriterApp,
shown below, demonstrates string output, primitive type data output,
and the wrapping of streams to gain greater capabilities. We first
wrap the System.out
object, which is an 8-bit stream, with an OutputStreamWriter
to obtain 16-bit streaming.
However, the OutputStreamWriter
class (see specifications)
provides only a few methods. So we wrap our OutputStreamWriter
object with PrintWriter,
which offers a full set of print()
and println()
methods for printing strings and primitive types.
|
import
java.io.*;
/**
* Demonstrate stream wrapping by writing text
to the
* console using the standard output from System.out
* wrapped with OutputStreamWriter and PrintWriter.
**/
public class PrintWriterApp
{
public static void main (String arg[]) {
// The System.out standard output
stream is already opened by default.
// Wrap in a new writer stream to
obtain 16 bit capability.
OutputStreamWriter writer = new
OutputStreamWriter (System.out);
// In turn, wrap the PrintWriter
stream around this output stream
// and use the second argument in
the constructor to turn
// on the autoflush.
PrintWriter print_writer = new PrintWriter
(writer,true);
// PrintWriter does autoflushing
and offers a println
// method that includes line return.
print_writer.println ("Text output
with PrintWriter.");
print_writer.println ("Primitives
converted to strings:");
boolean a_boolean = false;
byte a_byte = 114;
short a_short
= 1211;
int an_int = 1234567;
long a_long = 987654321;
float a_float
= 983.6f;
double a_double =
-4.297e-15;
print_writer.println (a_boolean);
print_writer.println (a_byte);
print_writer.println (a_short);
print_writer.println (an_int);
print_writer.println (a_long);
print_writer.println (a_float);
print_writer.println (a_double);
// PrintWriter doesn't throw IOExceptions
but instead
// offers the catchError() method
if( print_writer.checkError ())
{
System.out.println
("An output error occurred!" );
}
} // main
}// class PrintWriterApp
|
The output from this class goes as
Note that some wrapper stream classes include a
buffer that collects data until it is full and then the
whole buffer data set is sent to its destination in one operation.
This is more efficient than sending each byte one at a time because
of the overhead involved in any transfer.
To insure that data does not remain in a partially
filled buffer, you may need to invoke a flush method .
With both PrintStream
and PrintWriter,
you have the option of turning on an auto-flushing switch.
References & Web
Resources