在开发下载多个excel打包zip文件时遇到问题如下:
for (Workbook workbook : workbooks) {
ZipEntry zipEntry = new ZipEntry("数据导出" + i+ ".xlsx");
zipOutputStream.putNextEntry(zipEntry);
workbook.write(zipOutputStream);
zipOutputStream.closeEntry();
}
zipOutputStream.flush();
zipOutputStream.close();
在for循环中使用上述代码,第一个workbook 写入完成后,报错stream closed。
原因为XSSFWorkbook.write 会自动关闭流,导致后续执行时报stream closed。
解决方法如下:
1、创建一个ByteArrayOutputStream,先将workbook写入ByteArrayOutputStream中,然后在写入zipOutputStream,即使在写入ByteArrayOutputStream后将流关闭,也不会影响zipOutputStream。直接上代码:
ZipEntry zipEntry = new ZipEntry("数据导出" + i+ ".xlsx");
zipOutputStream.putNextEntry(zipEntry);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
bos.writeTo(zipOutputStream);
2、自己创建类继承ZipOutputStream 对象,并重写close方法。代码中zipOutputStream使用继承类,解决。
public class UncloseableZipOutputStream extends ZipOutputStream
{
OutputStream os;
public UncloseableZipOutputStream( OutputStream os )
{
super(os);
}
@Override
/** just flush but do not close */
public void close() throws IOException
{
flush();
}
public void reallyClose() throws IOException
{
super.close();
}
}