如何在 Java 中找到 ZipFile 条目的文件偏移量? [英] How can I find the file offset of a ZipFile entry in Java?

查看:34
本文介绍了如何在 Java 中找到 ZipFile 条目的文件偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ZipFile,我想创建一个数组,其中包含每个条目的偏移量/大小.这是为了让 C++ 层 (JNI) 可以直接读取这些子文件,而无需提取它们.

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.

我可以使用 entry.getCompressedSize() 获取文件的压缩大小,但我没有看到任何内容可以找出 zip 中文件的偏移量.

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?

推荐答案

我读到条目由 .entries() 以它们在文件中出现的确切顺序返回(不确定这是指实际文件还是标题条目.) 假设是这种情况,以下解决了问题:

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;
}

这适用于我的情况.但唯一需要注意的是,根据 ZIP 压缩规范,并不是所有 zip 文件中的文件都以与目录中完全相同的顺序存储.因为在我的情况下,我可以控制 zip 文件的构造,这不是问题,但是如果您使用来自不受控制的来源的 zip,这种方法可能不起作用.

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.

这篇关于如何在 Java 中找到 ZipFile 条目的文件偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆