O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Print Writers

The java.io.PrintWriter class is a subclass of java.io.Writer that contains the familiar print() and println() methods from System.out and other instances of PrintStream. It’s deliberately similar to the java.io.PrintStream class. In Java 1.0 PrintStream 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.

The main difference between PrintStream and PrintWriter is that PrintWriter handles multiple-byte and other non-ISO Latin-1 character sets properly. The other, more minor difference is that automatic flushing is performed only when println() is invoked, not every time a newline character is seen. Sun would probably like to deprecate PrintStream and use PrintWriter instead, but that would break too much existing code. (In fact, Sun did deprecate the PrintStream() constructors in 1.1, but they undeprecated them in Java 2.)

There are four constructors in this class:

public PrintWriter(Writer out)
public PrintWriter(Writer out, boolean autoFlush)
public PrintWriter(OutputStream out)
public PrintWriter(OutputStream out, boolean autoFlush)

The PrintWriter can send text either to an output stream or to another writer. If autoFlush is set to true, the PrintWriter is flushed every time println() is invoked.

The PrintWriter class implements the abstract write() method from java.io.Writer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required