java.io.IOException:流在 java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:66) 关闭

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

下面是代码片段。

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
            }                                                       
        }
    }             
}

读取一个无法读取其他文件的 'xls' 文件后出现异常。提前致谢

您正在调用 POIFSFileSystem(InputStream) 构造函数,即 documented 为:

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

(强调我的。)

这意味着您将在第一次迭代后关闭 ZipInputStream - 您不想那样做。

而是调用 POIFSFileSystem.createNonClosingInputStream:

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

换句话说:

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