Take a look at PrintStream's source.
It has two references to the underlying Writer textOut
and charOut
, one character-base, and one text-based (whatever that means). Also, it inherits a third reference to the byte-based OutputStream, called out
.
/**
* Track both the text- and character-output streams, so that their buffers
* can be flushed without flushing the entire stream.
*/
private BufferedWriter textOut;
private OutputStreamWriter charOut;
In the close()
method it closes all of them (textOut
is basically the same as charOut
).
private boolean closing = false; /* To avoid recursive closing */
/**
* Close the stream. This is done by flushing the stream and then closing
* the underlying output stream.
*
* @see java.io.OutputStream#close()
*/
public void close() {
synchronized (this) {
if (! closing) {
closing = true;
try {
textOut.close();
out.close();
}
catch (IOException x) {
trouble = true;
}
textOut = null;
charOut = null;
out = null;
}
}
}
Now, the interesting part is that charOut contains a (wrapped) referenced to the PrintStream itself (note the init(new OutputStreamWriter(this))
in the constructor )
private void init(OutputStreamWriter osw) {
this.charOut = osw;
this.textOut = new BufferedWriter(osw);
}
/**
* Create a new print stream.
*
* @param out The output stream to which values and objects will be
* printed
* @param autoFlush A boolean; if true, the output buffer will be flushed
* whenever a byte array is written, one of the
* <code>println</code> methods is invoked, or a newline
* character or byte (<code>'\n'</code>) is written
*
* @see java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
*/
public PrintStream(OutputStream out, boolean autoFlush) {
this(autoFlush, out);
init(new OutputStreamWriter(this));
}
So, the call to close()
will call charOut.close()
, which in turn calls the original close()
again, which is why we have the closing flag to cut short the infinite recursion.