Simple-Solution
Simple-Solution

Reputation: 4289

How to extract and read entries of zip file which is sent as a byte array

In a nutshell I'm trying to write a method which receives the Zip file as byte[] array, and what I want to do is to return the number of entries (the files) that are in the Zip file and test if they're 6 entries.

Here is what I've done so far, which throws FileNotFoundException on line 3

  public List<ZipEntry> extractZipEntries(byte[] content) throws IOException {
    List<ZipEntry> entries = new ArrayList<>();

    ZipFile zip = new ZipFile(content.toString()); //Line 3

    for (Enumeration<?> e = zip.entries(); e.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) e.nextElement();
        entries.add(entry);
    }
    return entries;
  }

test is here:

 List<ZipEntry> zipEntries = SomeClassName.extractZipEntries(content);
 assertTrue(zipEntries.size() == 6);

Also if possible suggest a better approach, but ideally what I doing above is straight forward here.

Thanks!

Upvotes: 5

Views: 8843

Answers (1)

jmn
jmn

Reputation: 564

Seeing as the source is a byte[], you'll need to use a ByteArrayInputStream to read the file.

public List<ZipEntry> extractZipEntries(byte[] content) throws IOException {
    List<ZipEntry> entries = new ArrayList<>();

    ZipInputStream zi = null;
    try {
        zi = new ZipInputStream(new ByteArrayInputStream(content));

        ZipEntry zipEntry = null;
        while ((zipEntry = zi.getNextEntry()) != null) {
            entries.add(zipEntry);
        }
    } finally {
        if (zi != null) {
            zi.close();
        }
    }
    return entries;
}

Upvotes: 6

Related Questions