我有一个带有返回流的静态方法的助手类:
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));
我的密码有效。
但是,根据Java文档, I应该关闭我的资源:
资源是程序完成后必须关闭的对象。try-语句确保在语句末尾关闭每个资源。
但是,当我实现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
如何确保,该资源将关闭,后,的使用?
发布于 2020-12-17 15:36:56
通常,调用方负责关闭/释放资源。
您可以在方法之外使用try-或try-finally构造,如下所示:
try (InputStream is = getDocument(aFile) {
//… do your stuff
}
如果我可以给您一个建议,请将其写在方法文档中:
/**
* The caller is required to close the returned {@link InputStream}
*/
public static InputStream getDocument(File file) throws IOException
发布于 2021-02-20 02:12:54
使用资源进行尝试与使用finally
的第二种方法具有相同的含义。除了返回基于此zipFile的inputStream之外,无法关闭zipFile。
通常,最好避免使用此帮助方法,并使用具有多个资源的资源的单一尝试:
try (
ZipFile zipFile = new ZipFile(file);
inputStream inputStream = zipFile.getInputStream(zipFile.getEntry("entry"));
) {
// Do stuff
} // Both zipFile and inputStream closed here implicitly
但是,如果需要创建这样的方法,则可以确保当流关闭时,zipFile对象也会被关闭。
从一个相关的问题ZipEntry在关闭ZipFile之后是否会持久化?
zipFile = new ZipFile(file);
InputStream zipInputStream = ...
return new InputStream() {
@Override
public int read() throws IOException {
return zipInputStream.read();
}
@Override
public void close() throws IOException {
// Better add try/catch around each close()
zipInputStream.close();
zipFile.close();
}
}
这样,当调用方法关闭它接收到的流时,zip文件也将被关闭。
https://stackoverflow.com/questions/65343694
复制相似问题