java.io.IOException: Stream closed at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:66)

Below is the code Snippet.

while (iterator.hasNext()) {
    FileItemStream item = iterator.next();
    InputStream in = item.openStream();
    ZipInputStream zin =new ZipInputStream(new BufferedInputStream(in));
    for (ZipEntry zipEntry;(zipEntry = zin.getNextEntry()) != null; )
    {
        System.out.println("reading zipEntry " + zipEntry.getName());
        if(zipEntry.getName().endsWith(".xls")){                    
            POIFSFileSystem fs = new POIFSFileSystem(zin);
            HSSFWorkbook wb = new HSSFWorkbook(fs); 
            HSSFSheet sheet = wb.getSheetAt(0);
            Iterator rows = sheet.rowIterator(); 
            while( rows.hasNext() ) { 
                ... some code here
            }                                                       
        }
    }             
}

I am getting an exception after reading one 'xls' file not able to read other files. Thanks in advance

Jon Skeet
people
quotationmark

You're calling the POIFSFileSystem(InputStream) constructor, which is documented as:

Create a POIFSFileSystem from an InputStream. Normally the stream is read until EOF. The stream is always closed.

(Emphasis mine.)

That means you're closing the ZipInputStream after the first iteration - you don't want to do that.

Instead, call POIFSFileSystem.createNonClosingInputStream:

Convenience method for clients that want to avoid the auto-close behaviour of the constructor.

In other words:

if (zipEntry.getName().endsWith(".xls")) {
   POIFSFileSystem fs = POIFSFileSystem.createNonClosingInputStream(zin);
   ...
}

people

See more on this question at Stackoverflow