从嵌入的 ZIP 档案中读取文件 [英] Reading files from an embedded ZIP archive

查看:32
本文介绍了从嵌入的 ZIP 档案中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌入在较大文件中的 ZIP 存档.我知道档案在较大文件中的起始偏移量及其长度.

I have a ZIP archive that's embedded inside a larger file. I know the archive's starting offset within the larger file and its length.

是否有任何 Java 库可以让我直接读取存档中包含的文件?我在思考 ZipFile.getInputStream().不幸的是,ZipFile 不适用于此用例,因为其构造函数需要一个独立的 ZIP 文件.

Are there any Java libraries that would enable me to directly read the files contained within the archive? I am thinking along the lines of ZipFile.getInputStream(). Unfortunately, ZipFile doesn't work for this use case since its constructors require a standalone ZIP file.

出于性能原因,我无法在打开 ZIP 文件之前将其复制到单独的文件中.

For performance reasons, I cannot copy the ZIP achive into a separate file before opening it.

澄清一下,我确实可以随机访问该文件.

edit: Just to be clear, I do have random access to the file.

推荐答案

我想出了一个快速的 hack(需要在这里和那里进行清理),但它从 ZIP 存档中读取文件的内容,这是嵌入在 TAR 中.它使用 Java6、FileInputStream、ZipEntry 和 ZipInputStream.'在我的本地机器上工作':

I've come up with a quick hack (which needs to get sanitized here and there), but it reads the contents of files from a ZIP archive which is embedded inside a TAR. It uses Java6, FileInputStream, ZipEntry and ZipInputStream. 'Works on my local machine':

final FileInputStream ins = new FileInputStream("archive.tar");
// Zip starts at 0x1f6400, size is not needed
long toSkip = 0x1f6400;
// Safe skipping
while(toSkip > 0)
    toSkip -= ins.skip(toSkip);

final ZipInputStream zipin = new ZipInputStream(ins);
ZipEntry ze;
while((ze = zipin.getNextEntry()) != null)
{
    final byte[] content = new byte[(int)ze.getSize()];
    int offset = 0;
    while(offset < content.length)
    {
        final int read = zipin.read(content, offset, content.length - offset);
        if(read == -1)
            break;
        offset += read;
    }
    // DEBUG: print out ZIP entry name and filesize
    System.out.println(ze + ": " + offset);
}
zipin.close();

这篇关于从嵌入的 ZIP 档案中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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