javaspring-bootapache-poizipinputstreammultipartfile

ZipInputStream is closes when reading first ZipEntry of Excel files


I'm uploading zip of excel files as multipart file, but when I create Workbook object of first file, the stream gets closed and I'm not able to read next files. its working with single file in zip but not with multiple files. can anybody help? TIA.

       try {
            ZipInputStream zis = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry zipEntry;
            while((zipEntry = zis.getNextEntry()) != null) {
                XSSFWorkbook workbook = new XSSFWorkbook(zis);
                readWorkbook(workbook);
            }
            zis.close();
        } catch (Exception e) {
            LOG.error(e);
        }

Solution

  • only option is to wrap it so you can intercept close() and prevent it from closing the zip. Something like:

    var wrapper = new FilterInputStream(zis) {
      @Override public void close() {}
    }
    

    Then pass wrapper and not zis to new XSSFWorkbook.

    NB: WARNING - your code is severely hampered, essentially buggy. You need to ensure you close that ZipInputStream at the very end, and you're not doing that now. Your exception handling is really bad. You must end all exception blocks with a hard exit, just logging it isn't good enough. throw new RuntimeException("uncaught", e); is the fallback option (many IDEs ship with e.printStackTrace() as default. This is a known extremely stupid default, update your IDE to fix this. Use try-with-resources as well to ensure closing always happens (just calling close() isn't good enough; that close() call you do have in your snippet won't be invoked if exceptions occur.