Retrieving ZipFile Entries When Reading from Byte [] (Java)

I have a zip file whose contents are represented as byte [] , but the source file object is not available . I want to read the contents of each of the entries. I can create a ZipInputStream from ByteArrayInputStream from bytes and can read the records and their names. However, I do not see an easy way to extract the contents of each entry.

(I watched Apache Commons, but I don’t see an easy way there).

UPDATE @ Rich code seems to solve the problem, thanks

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

+4
source share
3 answers

If you want to process nested zip entries from a stream, see this answer for ideas. Since internal records are listed sequentially, they can be processed by obtaining the size of each record and reading that there are many bytes from the stream.

Updated with an example that copies each entry to the standard version:

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; } } 
+6
source

It actually uses ZipInputStream as an InputStream (but does not close it at the end of each record).

0
source

It's a little tricky to figure out the start of the next ZipEntry. See This Example, Included in JDK 6,

 public static void main(String[] args) { try { ZipInputStream is = new ZipInputStream(System.in); ZipEntry ze; byte[] buf = new byte[128]; int len; while ((ze = is.getNextEntry()) != null) { System.out.println("----------- " + ze); // Determine the number of bytes to skip and skip them. int skip = (int)ze.getSize() - 128; while (skip > 0) { skip -= is.skip(Math.min(skip, 512)); } // Read the remaining bytes and if it printable, print them. out: while ((len = is.read(buf)) >= 0) { for (int i=0; i<len; i++) { if ((buf[i]&0xFF) >= 0x80) { System.out.println("**** UNPRINTABLE ****"); // This isn't really necessary since getNextEntry() // automatically calls it. is.closeEntry(); // Get the next zip entry. break out; } } System.out.write(buf, 0, len); } } is.close(); } catch (Exception e) { e.printStackTrace(); } } 
0
source

All Articles