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

时间:2014-06-17 22:37:25

标签: java inputstream zipfile

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

1 个答案:

答案 0 :(得分:4)

以下是InputStream from ZipFile的实施:

/*
* 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();

请注意对#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();
    }
}

另一种方法是缓冲它:

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

显然现在已经全部进入内存,所以你的数据需要合理的大小。