ZipFile关闭后ZipEntry是否仍然存在?

Oct*_*ami 6 java inputstream zipfile

我目前在我的库中有一个似乎合理的资源泄漏,因为我保持一个ZipFile打开,以便某个ZipEntry的返回的InputStream没有关闭.但是,关闭返回的InputStream不会关闭ZipFile的其余部分,所以我坚持打开它.有没有办法安全地关闭ZipFile并保持InputStream返回?

Kon*_*ong 5

这是来自 ZipFileInputStream的实现:

/*
* Inner class implementing the input stream used to read a
* (possibly compressed) zip file entry.
*/
private class ZipFileInputStream extends InputStream {

   ...

   public int read(byte b[], int off, int len) throws IOException {
       if (rem == 0) {
           return -1;
       }
       if (len <= 0) {
           return 0;
       }
       if (len > rem) {
           len = (int) rem;
       }
       synchronized (ZipFile.this) {
           ensureOpenOrZipException();
Run Code Online (Sandbox Code Playgroud)

注意对 的调用#ensureOpenOrZipException

因此,很遗憾,您的问题的答案是否定的,无法保持信息流开放。

您可以做的是包装并挂钩 InputStream 上的 #close 以关闭您的 zip 文件:

InputStream zipInputStream = ...
return new InputStream() {
    @Override
    public int read() throws IOException {
        return zipInputStream.read();
    }
    @Override
    public void close() throws IOException {
        zipInputStream.close();
        zipFile.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是缓冲它:

InputStream myZipInputStream = ...
//Read the zip input stream fully into memory
byte[] buffer = ByteStreams.toByteArray(zipInputStream);
zipFile.close();
return new ByteArrayInputStream(buffer);
Run Code Online (Sandbox Code Playgroud)

显然,这一切现在都已进入内存,因此您的数据需要具有合理的大小。