Java extract zip Unexpected end of ZLIB input stream

I create a program that will extract the zip and then insert the files into the database, every so often I get an error

java.lang.Exception: java.io.EOFException: Unexpected end of ZLIB input stream

I cannot pinpoint the reason for this, since the extraction code is almost the same as all other code that you can find on the Internet. My code is as follows:

public void extract(String zipName, InputStream content) throws Exception {

    int BUFFER = 2048;

    //create the zipinputstream 
    ZipInputStream zis = new ZipInputStream(content);

    //Get the name of the zip
    String containerName = zipName;

    //container for the zip entry
    ZipEntry entry;

    // Process each entry
    while ((entry = zis.getNextEntry()) != null) {

        //get the entry file name
        String currentEntry = entry.getName();

        try {

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                // establish buffer for writing file
                byte data[] = new byte[BUFFER];
                int currentByte;

                // read and write until last byte is encountered
                while ((currentByte = zis.read(data, 0, BUFFER)) != -1) {

                    baos.write(data, 0, currentByte);
                }

                baos.flush(); //flush the buffer 

                //this method inserts the file into the database
                insertZipEntry(baos.toByteArray());

                baos.close();

        } 
        catch (Exception e) {
            System.out.println("ERROR WITHIN ZIP " + containerName);
        }
    }
}
+3
source share
3 answers

This is probably due to this JVM error (JVM-6519463): http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=53ede10dc8803210b03577eac43?bug_id=6519463

Previously, I had about one or two errors on 1000 randomly generated documents, I applied the proposed solution (catch an EOFException and do nothing with it), and I have no more errors.

+2

, Zip . .

+1

Never try to read more bytes than the record contains. Call ZipEntry.getSize () to get the actual size of the record, then use this value to track the number of bytes remaining in the record when reading from it. See below:

try{    

   ...

   int bytesLeft = (int)entry.getSize();
   while ( bytesLeft>0 && (currentByte=zis.read(data, 0, Math.min(BUFFER, bytesLeft))) != -1) {
     ...
  }

  ...

  }
-1
source

Source: https://habr.com/ru/post/1795088/


All Articles