看看 PrintStream 的源代码。
它有两个对底层 WritertextOut
和的引用charOut
,一个是基于字符的,一个是基于文本的(不管是什么意思)。此外,它继承了对基于字节的 OutputStream 的第三个引用,称为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;
在close()
方法中它关闭了所有这些(textOut
与 基本相同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;
}
}
}
现在,有趣的部分是 charOut 包含一个(包装的)引用 PrintStream 本身(注意init(new OutputStreamWriter(this))
构造函数中的)
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));
}
因此,调用close()
将调用charOut.close()
,而后者又再次调用原来的close()
,这就是为什么我们有关闭标志来缩短无限递归。