7

令我惊讶的是,以下代码两次打印出“关闭”。通过调试器运行,似乎MyPrintStream.close()调用super.close(),最终MyPrintStream.close()再次调用。

    
import java.io.*;

public class PrintTest
{
    static class MyPrintStream extends PrintStream
    {
        MyPrintStream(OutputStream os)
        {
            super(os);
        }

        @Override
        public void close()
        {
            System.out.println("Close");
            super.close();
        }
    }

    public static void main(String[] args) throws IOException
    {
        PrintStream ps = new MyPrintStream(new FileOutputStream(File.createTempFile("temp", "file")));
        ps.println("Hello");
        ps.close();
    }
}

为什么会这样?我不应该扩展 PrintStream 吗?

4

2 回答 2

11

如果您在调试器中查看代码并在close()方法中设置断点,它将显示在调用您的close()方法的堆栈跟踪:

  1. 你的主要方法
  2. sun.nio.cs.StreamEncoder$CharsetSE.implClose() 第 431 行

后者的完整堆栈跟踪如下所示:

PrintTest$MyPrintStream.close() line: 20    
sun.nio.cs.StreamEncoder$CharsetSE.implClose() line: 431 [local variables unavailable]  
sun.nio.cs.StreamEncoder$CharsetSE(sun.nio.cs.StreamEncoder).close() line: 160 [local variables unavailable]    
java.io.OutputStreamWriter.close() line: 222 [local variables unavailable]  
java.io.BufferedWriter.close() line: 250 [local variables unavailable]  
PrintTest$MyPrintStream(java.io.PrintStream).close() line: 307  
PrintTest$MyPrintStream.close() line: 20    
PrintTest.main(java.lang.String[]) line: 27 

可悲的是,尽管我不知道为什么StreamEncoder 会回调到您的 PrintStream 中,因为我的 IDE 没有 sun.nio.cs.StreamEncoder 的源附件 :( 这是 JDK 6 顺便说一句,如果这很重要。

顺便说一句,如果您问这个问题是因为您注意到close()方法中的自定义代码运行了两次,那么您真的应该检查 if this.closingPrintStream.close()将此设置为 true (以及类的评论状态/* To avoid recursive closing */)。

于 2009-05-12T13:47:41.287 回答
1

看看 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(),这就是为什么我们有关闭标志来缩短无限递归。

于 2009-05-12T22:41:19.700 回答