java - try-with-resource 关闭序列 : FileInputStream close executed three times

标签 java debugging java-7 try-with-resources

我正在 OS X 上使用 Java 8 尝试一个简单的 try-with-resource 示例。 我看到一些奇怪的行为。首先,以下是我正在运行的代码:

 public void test() {

        try( FileInputStream fin = new FileInputStream("/tmp/test");
             FileOutputStream fout = new FileOutputStream("/tmp/test1")
                ){

            System.out.println("Nothing here");
            System.out.println("Nothing here");
        }catch (Exception e) {
            System.err.println("Error "  + e);
        }
    }

应用程序运行良好,并按预期打印了两次 Nothing here。 当我在 Debug模式(IntelliJ idea)下运行它时,执行在 FileInputSteam::close() 处暂停两次,然后在 FileOutputStream::close() 处暂停,然后再次暂停在 FileInputStream::close() - 为了检查此行为的来源,我通过 jad-gui 查看了 .class 文件。它显示以下代码:

public void test()
  {
    try
    {
      FileInputStream fin = new FileInputStream("/tmp/test");Throwable localThrowable6 = null;
      try
      {
        FileOutputStream fout = new FileOutputStream("/tmp/test1");Throwable localThrowable7 = null;
        try
        {
          System.out.println("Nothing here");
          System.out.println("Nothing here");
        }
        catch (Throwable localThrowable1)
        {
          localThrowable7 = localThrowable1;throw localThrowable1;
        }
        finally {}
      }
      catch (Throwable localThrowable4)
      {
        localThrowable6 = localThrowable4;throw localThrowable4;
      }
      finally
      {
        if (fin != null) {
          if (localThrowable6 != null) {
            try
            {
              fin.close();
            }
            catch (Throwable localThrowable5)
            {
              localThrowable6.addSuppressed(localThrowable5);
            }
          } else {
            fin.close();
          }
        }
      }
    }
    catch (Exception e)
    {
      System.err.println("Error " + e);
    }
  }

这更令人困惑。

为什么反编译后的代码没有显示任何调用 FileOutputStream::close() - 是jd-gui的问题吗?

为什么在调试过程中控制两次 FileInputStream::close() 首先?这是一些错误还是它应该如何工作?

最佳答案

请参阅@jb-nizet 的评论,您的反编译器没有显示正确的内容,这解释了您的问题 1。

对于问题 2,请查看调试器中的 Stream.path 变量。在我的系统上,这不是您的 Streams openend,而是 Java 8 内部文件,例如“/opt/Oracle_Java/jdk1.8.0_40/jre/lib/tzdb.dat”、“/opt/Oracle_Java/jdk1.8.0_40/jre/lib/meta-index”和类本身。但我只有一个输入流“/tmp/test”调用和一个输出流“/tmp/test1”调用。

关于java - try-with-resource 关闭序列 : FileInputStream close executed three times,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604340/

相关文章:

JavaFX WebView 捕获来自 javascript 的 post 请求

java - Eclipse提供 "Failed to create the Java Virtual Machine"

C++: 程序 "Not Responding"执行时

.net - 在windbg 中调试.Net 字符串值

debugging - 在 arm7 上启用浮点异常时 fpscr 寄存器未更新,未生成 SIGFPE

java - 我怎么知道 BufferedReader 是否与 DataInputStream 链接在一起?

java - Java MethodHandles 可以被认为与一流的功能相同吗?

java - 使用类定位标签元素

java - 获取子节点之前的父节点的字符串内容

java - ClassCastException 字符串到 MValue,java 8