下面是DownFileUtils类中的代码,找了好久都找不出问题。我明明没有在前面的代码中关闭流。为什么会报io流已关闭异常呢?请各位帮忙!!
(有时候报io异常有时候报response异常)
private static byte[] createZip(String sourceFilePath) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
// 将目标文件打包成zip导出
File file = new File(sourceFilePath);
handlerFile(zip, file, "附件");
// 无异常关闭流,它将无条件的关闭一个可被关闭的对象而不抛出任何异常。
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
@SneakyThrows
public static void exportZip(HttpServletResponse response, String sourceFilePath, String fileName, boolean isBatch, Predicate<MultipartFile> predicate) {
// 默认文件名以时间戳作为前缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String downloadName = fileName + "-" + sdf.format(new Date()) + ".zip";
// 将文件进行打包下载
boolean b = false;
OutputStream os = null;
File zip = null;
try {
os = response.getOutputStream();
// 接收压缩包字节
byte[] data = createZip(sourceFilePath);
//上传文件到文件服务器
if (isBatch) {
zip = ZipUtil.zip(sourceFilePath, Charset.forName("UTF-8"));
FileInputStream fis = new FileInputStream(zip);
MultipartFile file = new MockMultipartFile("file", downloadName, "text/plain", fis);
b = predicate.test(file);
} else {
response.reset();
response.setCharacterEncoding("UTF-8");
response.addHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
// 下载文件名乱码问题
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "UTF-8"));
//response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + downloadName);
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
//org.apache.commons.io下的类
IOUtils.write(data, os);
}
} catch (Exception e) {
log.info("下载异常");
e.printStackTrace();
} finally {
os.flush();
os.close();
if (isBatch) {
// 删除临时文件
zip.delete();
}
deleteDir(new File(sourceFilePath));
}
}
下面是异常日志: