【发布时间】:2020-12-17 15:32:40
【问题描述】:
我有一个带有返回流的静态方法的辅助类:
public static InputStream getDocument(File file) throws IOException {
ZipFile zipFile = new ZipFile(file);
return zipFile.getInputStream(zipFile.getEntry("entry"));
}
另一个类访问该方法并使用返回的流:
InputStream is = MyClass.getDocument(new File(str));
我的代码有效。
但是,according to the Java Documentation, 我应该关闭我的资源:
资源是程序完成后必须关闭的对象。 try-with-resources 语句确保每个资源在语句结束时关闭。
但是,当我实现try-with-resources:
public static InputStream getDocument(File file) throws IOException {
try (ZipFile zipFile = new ZipFile(file);) {
return zipFile.getInputStream(zipFile.getEntry("entry"));
}
}
或try-finally:
public static InputStream getDocument(File file) throws IOException {
InputStream is = null;
try {
ZipFile zipFile = new ZipFile(docx);
is = zipFile.getInputStream(zipFile.getEntry("entry"));
return is;
} finally {
is.close();
}
}
我得到一个例外:
java.io.IOException: Stream closed
如何确保该资源将在使用后被关闭?
【问题讨论】:
-
调用者负责关闭资源
-
@tkruse 这个问题怎么重复?
-
try with resources 添加一个隐式 finally 块,在该块中它会关闭资源。因此,在这两种情况下,资源(流)都在代码块的末尾关闭。所以我们别无选择,只能在方法调用站点关闭资源。
标签: java inputstream autocloseable