从byte [](Java)读取时提取ZipFile条目的内容 [英] extracting contents of ZipFile entries when read from byte[] (Java)

查看:135
本文介绍了从byte [](Java)读取时提取ZipFile条目的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个zip文件,其内容显示为byte [] 但原始文件对象无法访问。我想阅读每个条目的内容。我能够从字节的ByteArrayInputStream创建一个ZipInputStream,并可以读取条目及其名称。但是我看不到一种简单的方法来提取每个条目的内容。

I have a zip file whose contents are presented as byte[] but the original file object is not accessible. I want to read the contents of each of the entries. I am able to create a ZipInputStream from a ByteArrayInputStream of the bytes and can read the entries and their names. However I cannot see an easy way to extract the contents of each entry.

(我看过Apache Commons但是看不到那么简单的方法)。

(I have looked at Apache Commons but cannot see an easy way there either).

更新 @ Rich的代码似乎解决了这个问题,谢谢

UPDATE @Rich's code seems to solve the problem, thanks

QUERY 为什么这两个例子的乘数都是* 4(128/512和1024 * 4)?

QUERY why do both examples have a multiplier of * 4 (128/512 and 1024*4) ?

推荐答案

如果你希望从流处理嵌套拉链条目,参见这个答案的想法。因为内部条目是按顺序列出的,所以可以通过获取每个条目的大小并从流中读取那么多字节来处理它们。

If you want to process nested zip entries from a stream, see this answer for ideas. Because the inner entries are listed sequentially they can be processed by getting the size of each entry and reading that many bytes from the stream.

更新了复制每个条目的示例标准输出:

Updated with an example that copies each entry to Standard out:

ZipInputStream is;//obtained earlier

ZipEntry entry = is.getNextEntry();

while(entry != null) {
    copyStream(is, out, entry);

    entry = is.getNextEntry();
}
...

private static void copyStream(InputStream in, OutputStream out,
        ZipEntry entry) throws IOException {
    byte[] buffer = new byte[1024 * 4];
    long count = 0;
    int n = 0;
    long size = entry.getSize();
    while (-1 != (n = in.read(buffer)) && count < size) {
        out.write(buffer, 0, n);
        count += n;
    }
}

这篇关于从byte [](Java)读取时提取ZipFile条目的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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