Dainius Java
Dainius Java

Reputation: 125

Java ZipEntry to bytes array

here is my code:

final InputStream inputStream = MY_RECEIVED_INPUT_STREAM;
ZipInputStream zis = new ZipInputStream(inputStream);

ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
        zipEntry = zis.getNextEntry();
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    }
zis.closeEntry();
zis.close();

I receive zip file with many files inside. I want to write these files to database. What I want is to get bytes from each and every ZipEntry and save them to database as Blob (xxxxxx.... part). How can I get bytes from zipEntry? I don't have ZipFile, so I can't use something like this:

InputStream stream = zipFile.getInputStream(entry);

or

byte[] bytes = IOUtils.readAllBytes(zipFile.getInputStream(entry));

Thanks in advance.

Upvotes: 1

Views: 3022

Answers (2)

Richard Kotal
Richard Kotal

Reputation: 189

You can use something like this:

    InputStream is = MY_RECEIVED_INPUT_STREAM;
    BufferedInputStream bis = null;
    ZipInputStream zis = null;
    ByteArrayOutputStream out = null;
    String name = null;
    byte[] b = new byte[8192];
    int len = 0;

    try {
        bis = new BufferedInputStream(is);
        zis = new ZipInputStream(bis);

        ZipEntry zipEntry = null;
        while ((zipEntry = zis.getNextEntry()) != null) {
            //name of file
            name = zipEntry.getName();

            if (zipEntry.isDirectory()) {
                //I'm skipping directories in this example
                continue;
            }

            out = new ByteArrayOutputStream();

            while ((len = zis.read(b)) > 0) {
                out.write(b, 0, len);
            }

            //save to DB - db_save(String file_name, byte[] file_bytes)
            db_save(name,out.toByteArray());
            out.close();
        }
    } finally {
        if (zis != null) {
            zis.close();
        }
        if (bis != null) {
            bis.close();
        }
        if (is != null) {
            is.close();
        }

    }

Upvotes: 3

drekbour
drekbour

Reputation: 3091

ZipFile makes this easier to read but the basic rule is that the ZipInputStream is lined up to the content relating to the current ZipEntry. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/zip/ZipInputStream.html#read(byte%5B%5D,int,int)

Read directly from zis until 0 and don't close() until all entries are handled.

    ZipEntry zipEntry;
    while ((zipEntry = zis.getNextEntry()) != null) {
      // xxx Do BLOB creation
      zis.transferTo(outputStream); // Java9
    }

(PS You don't need to call closeEntry())

Upvotes: 2

Related Questions