System.out is the first output stream most Java programmers encounter. System.err is probably the second. Both are instances of thejava.io.PrintStreamclass.PrintStreamis a subclass ofFilterOutputStreamthat converts numbers and objects to text.System.outis 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 makesSystem.outeasy to use in quick-and-dirty hacks and simple examples, while simultaneously making it unsuitable for production code, which should use thejava.io.PrintWriterclass (discussed in Chapter 20) instead.
PrintStreamis not limited to the console.PrintStreamis a filter stream and thus can be connected to any other output stream: aFileOutputStream, aByteArrayOutputStream, aTelnetOutputStream, or anything else you write to. Three constructors can be used to chain aPrintStreamto an underlying stream:
public PrintStream(OutputStream out) public PrintStream(OutputStream out, boolean autoFlush) public PrintStream(OutputStream out, boolean autoFlush, String encoding) throws UnsupportedEncodingException
Theoutargument is just the underlying output stream. TheautoFlushargument is aboolean. If itístrue, the stream is flushed every time a linefeed character (\n) or byte is written, aprintln()method is invoked, or a byte array is written. Theencoding argument names the character encoding used to convert strings to bytes. The last option is available only in Java 1.4 and later. Print streams in Java 1.3 and earlier (and all print streams created with the first two constructors) use the local systemís default encoding, whatever that may be. Often this is not the encoding you need, so you should specify the encoding explicitly if possible.
Java 5 added four more constructors, though these are mostly just conveniences. They allow you to create aPrintStreamthat will write data in a file. The file to be written is specified with either ajava.io.Fileobject (which will be discussed in Chapter 17) or aString containing the filename. You can also specify the character encoding used to write the file:
public PrintStream(String fileName) throws FileNotFoundException public PrintStream(String fileName, String encoding) throws FileNotFoundException, UnsupportedEncodingException public PrintStream(File file) throws FileNotFoundException public PrintStream(File file, String encoding) throws FileNotFoundException, UnsupportedEncodingException
These constructors donít accomplish anything that chaining aPrintStreamto aFileOutputStreamwonít do.