java.io.IOException:Streamclosed的问题排查最近开发“导出数据⽣成⽂件”功能时使⽤到多处OutputStream流操作。
如导出excel⽂件:
java stream//创建outputStream
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition",
"attachment;filename="+ at(".zip"),"UTF-8"));
outputStream = OutputStream();
//写⼊
wb.write(outputStream);
outputStream.flush();
如导出zip⽂件:
//创建zipOutputStream
public static void setZipOutputStream(HttpServletResponse response, String zipName)throws IOException {
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition",
"attachment;filename="+ at(".zip"),"UTF-8"));
outputStream =new OutputStream());
}
//excel压缩到zip
public static void excelToZipEntry(SXSSFWorkbook workbook, String excelName)throws IOException {
File tmpFile = ateTempFile("poi-sxssf-template",".xlsx");
boolean deleted;
try(FileOutputStream os =new FileOutputStream(tmpFile);
FileInputStream fileInputStream =new FileInputStream(tmpFile);
BufferedInputStream bufferedInputStream =new BufferedInputStream(fileInputStream)){
workbook.write(os);
ZipEntry entry =new ZipEntry(excelName +".xlsx");
outputStream.putNextEntry(entry);
byte[] buffer =new byte[1024];
int len;
while((len = ad(buffer))!=-1){
outputStream.write(buffer,0, len);
}
}finally{
outputStream.closeEntry();
deleted = tmpFile.delete();
if(!deleted){
throw new IOException("Could not delete temporary file after processing: "+ tmpFile);
}
}
}
//压缩pdf到zip
public static void pdfToZipEntry(String pdfFileName,byte[] bytes)throws IOException {
try(ByteArrayInputStream byteArrayInputStream =new ByteArrayInputStream(bytes)){
ZipEntry entry =new ZipEntry(pdfFileName +".pdf");
outputStream.putNextEntry(entry);
byte[] buffer =new byte[1024];
int len;
while((len = ad(buffer))!=-1){
outputStream.write(buffer,0, len);
}
}finally{
outputStream.closeEntry();
}
}
经常会遇到的异常就是:
java.io.IOException: Stream closed
原因在于:
每次往流⾥写数据的源代码⾥,都会检查⼀下流是否关闭,关闭就抛 java.io.IOException: Stream closed 虽然知道这个异常的意思,但是在关闭outputstream的原因的时候,还是花费了⼀些时间。
例如:
在ZipFileUtil是⼀个⽣成zip⽂件的⼯具类。
ZipFileUtil.class⾥创建了⼀个全局唯⼀的OutputStream,但是在创建的时候,却使⽤了如下⽅式创建:
public class ZipFileUtil {
private static ZipOutputStream outputStream;
private static File file;
public static void setZipOutputStream(String filePath){
file =new File(filePath);
try(FileOutputStream fileOutputStream =new FileOutputStream(file)){
outputStream =new ZipOutputStream(fileOutputStream);
}catch(Exception e){
<("创建ZipOutputStream失败,filePath={}", filePath, e);
}
outputStream =new ZipOutputStream(fileOutputStream);
}
}
try-catch的⽅式创建流,在try-catch代码结束的时候会⾃动关闭OutputStream,
所以在后续插⼊数据的时候,直接抛出了java.io.IOException: Stream closed
修改⽅案:
public static void setZipOutputStream(String filePath){
file =new File(filePath);
try{
fileOutputStream =new FileOutputStream(file);
}catch(FileNotFoundException e){
e.printStackTrace();
}
outputStream =new ZipOutputStream(fileOutputStream);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。