Chapter 7. Print Streams

System.out is the first output stream most Java programmers encounter. System.err is probably the second. Both are instances of the java.io.PrintStream class. PrintStream is a subclass of FilterOutputStream that converts numbers and objects to text. System.out is primarily used for simple, character-mode applications and for debugging. Its raison d'étre is convenience, not robustness; print streams ignore many issues involved in internationalization and error checking. This makes System.out easy to use in quick-and-dirty hacks and simple examples, while simultaneously making it unsuitable for production code, which should use the java.io.PrintWriter class (discussed in Chapter 20) instead.

PrintStream is not limited to the console. PrintStream is a filter stream and thus can be connected to any other output stream: a FileOutputStream, a ByteArrayOutputStream, a TelnetOutputStream, or anything else you write to. Three constructors can be used to chain a PrintStream to an underlying stream:

public PrintStream(OutputStream out)
public PrintStream(OutputStream out, boolean autoFlush)
public PrintStream(OutputStream out, boolean autoFlush, String encoding)
 throws UnsupportedEncodingException

The out argument is just the underlying output stream. The autoFlush argument is a boolean. If it’s true, the stream is flushed every time a linefeed character (\n) or byte is written, a println( ) method is invoked, or a byte array is written. The encoding argument names ...

Get Java I/O, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.