Readers Writers  «Prev  Next»


Lesson 2PrintWriter and PrintStream
ObjectiveExplore how to use PrintWriter in place of PrintStream.

PrintWriter and PrintStream

Difference between PrintWriter and PrintStream

The main difference between the PrintStream and PrintWriter classes is that the PrintWriter class properly handles multi-byte and other non-ISO Latin-1 character sets.
The other, more minor, difference is that PrintWriter only flushes the stream when println() is invoked, not every time a newline character is seen, like in the middle of a print call. Sun would probably like to deprecate PrintStream and use code>PrintWriter instead, but that would break too much existing code.
The java.io.PrintWriter class is a subclass of java.io.Writer that provides the familiar print() and println() methods. It's very similar to the java.io.PrintStream class.
In Java 1.0, the PrintStream class was used for text-oriented output, but it didn't handle multiple byte character sets particularly well (or really at all). In Java 1.1 and later, streams are only for byte-oriented and numeric output. Writers should be used when you want to output text.

PrintWriter Class


PrintWriter(OutputStream outputStream, boolean flushingOn)
Here, outputStream is an object of type OutputStream, and flushingOn controls whether Java flushes the output stream every time a println( ) method (among others) is called. If flushingOn is true, flushing automatically takes place. If false, flushing is not automatic. PrintWriter supports the print( ) and println( ) methods. Thus, you can use these methods in the same way as you used them with System.out. If an argument is not a simple type, the PrintWriter methods call the object's toString( ) method and then display the result. To write to the console by using a PrintWriter, specify System.out for the output stream and automatic flushing. For example, this line of code creates a PrintWriter that is connected to console output:

PrintWriter pw = new PrintWriter(System.out, true);