0

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);
        }
  • Have you tried POI 5.2.0 (latest release)? - ` public XSSFWorkbook(InputStream is) throws IOException { this(is, false); }` -- where false controls whether the input stream is closed or not – PJ Fanning Jan 25 '22 at 14:52

2 Answers2

0

When reading from a Zipfile, you have an InputStream for the archive. Then you traverse the different entries in there and for each of them you again have an InputStream to read from. Make sure you do not close the entries' InputStreams as that event will close the archive stream.

In your case it may be that the constructor for XSSFWorkbook or the readWorkbook method is closing the stream.

Queeg
  • 7,748
  • 1
  • 16
  • 42
0

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.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Thanks! this worked.. also thanks for suggestions, this was a sample code just to show the issue. the actual code is way different than this. – Balkrishna Kardam Jan 27 '22 at 09:07