首页 > 解决方案 > try-with-resources 中的 DigestInputStream 是否会关闭原始 InputStream?

问题描述

如果我在 try-with-resources 块中InputStream声明 a ,是否需要显式关闭原始文件?DigestInputStream

例子:

InputStream is = ...;
MessageDigest md = ...;

try (final DigestInputStream digestInputStream = new DigestInputStream(is, md)) {
    // Read the stream...
}

我是否需要手动关闭?

标签: javastreamtry-catch

解决方案


因为在 try-with-resources 块中声明它DigestInputStreamAutoCloseable,您不需要手动关闭它。

文件来自AutoCloseable

{@code AutoCloseable} 对象的 {@link #close()} 方法在退出已在资源规范标头中声明对象的 {@code try}-with-resources 块时自动调用。

此外,FilterInputStream覆盖了close关闭 used 的方法InputStream


推荐阅读