gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:02:52 26 4
gpt4 key购买 nike

我正在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com