关闭InputStream是否释放资源,即使它抛出?

时间:2013-10-08 22:29:02

标签: java file-io inputstream

只是一个简单的问题。鉴于此代码:

try {
    // operation on inputstream "is"
} finally {
    try {
        is.close();
    } catch (IOException ioe) {
        //if ioe is thrown, will the handle opened by 'is' be closed?
    }
}

如果close()抛出,文件句柄是否仍在(并泄露),还是已经关闭?

1 个答案:

答案 0 :(得分:3)

不可靠。如果is.close()抛出,is可能不会被标记为已关闭。无论如何,你无能为力。你不知道is的内部。 Java 7等价物只是隐藏了这个问题。

try (InputStream is = Files.newInputStream(...)) {
    // Stuff with is.
} catch (IOException is) {
    ...  // Handles exceptions from the try block.
}  // No finally. Handled by try-with-reources

如果自动关闭抛出,则异常是被抑制的异常,并且您永远不会知道是否或何时回收文件句柄。