How can I find the file offset of a ZipFile entry

2019-07-15 08:01发布

I have a ZipFile and I'd like to create an array with the offsets/sizes of each entry in it. This is so that a C++ layer (JNI) can read these subfiles directly without having to extract them.

I can get the file's compressed size using entry.getCompressedSize() but I don't see anything to find out the offset of the file within the zip.

Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements())
{
    ZipEntry zip = (ZipEntry)zipEntries.nextElement();
    //long offset = ?
    long fileSize = zip.getCompressedSize();
}

Any easy way to get this?

标签: java zip
1条回答
姐就是有狂的资本
2楼-- · 2019-07-15 08:22

I read that entries are returned by .entries() in the exact order they occur in the file (unsure if this refers to the actual file or the header entry.) Assuming this to be the case the following solves the problem:

Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
long offset = 0;
while (zipEntries.hasMoreElements())
{
    ZipEntry entry = (ZipEntry)zipEntries.nextElement();
    long fileSize = 0;
    long extra = entry.getExtra() == null ? 0 : entry.getExtra().length;
    offset += 30 + entry.getName().length() + extra;
    if(!entry.isDirectory())
    {
        fileSize = entry.getCompressedSize();

        // Do stuff here with fileSize & offset
    }    
    offset += fileSize;
}

This is working for my case. The only thing to note though is that according to the ZIP compression spec, it's not a given that in all zip files the files be stored in exactly the same order as in the directory. Since in my case I have control of the construction of the zip file this isn't a problem but this approach may not work if you work with zips from an uncontrolled source.

查看更多
登录 后发表回答