extracting contents of ZipFile entries when read from byte[] (Java)

peter.murray.rust picture peter.murray.rust · Oct 7, 2009 · Viewed 7.8k times · Source

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.

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

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

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

Answer

Rich Seller picture Rich Seller · Oct 7, 2009

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