编辑
2024-04-25
遇到的问题
00
请注意,本文编写于 369 天前,最后修改于 369 天前,其中某些信息可能已经过时。

目录

前提
排查

前提

业务需要,得通过javaweb下载用户的个人信息的pdf,多个人批量下载时就需要将pdf文件存放在zip类型中,但是下载得到的文件解压时提示错误,里面的文件大小为空

排查

首先,生成zip文件时服务器并未提示,系统错误,导致的文件异常,上网查找发现,可能是流未关闭的问题,然后我使用的是try(reason) catch的方式,流会自动关闭 代码如下

java
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(baos)) { // 遍历文件数据列表,将每个byte数组添加为zip条目 for (int i = 0; i < fileDataList.size(); i++) { byte[] fileData = JSON.toJSONBytes(fileDataList.get(i).get("bytes")); String entryName = (String) fileDataList.get(i).get("fileName"); ZipEntry zipEntry = new ZipEntry(entryName); zipOut.putNextEntry(zipEntry); zipOut.write(fileData); zipOut.closeEntry(); } zipOut.flush(); baos.flush(); // 设置HTTP响应头 response.setContentType("application/zip"); String fileName = String.format("%s_%s_全病案_%s.zip", province, name, DateUtil.format(new Date(), "yyyyMMdd")); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); // 将zip数据写入响应流 IoUtil.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); }

深入挖掘

自动关闭流是在整个业务流程走完之后才会一一关闭流,但是zipout这个流使用完毕之后就需要立即关闭, 即在 zipOut.flush();之后就需要关闭

修改代码后就不会提示了

java
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(baos)) { // 遍历文件数据列表,将每个byte数组添加为zip条目 for (int i = 0; i < fileDataList.size(); i++) { byte[] fileData = JSON.toJSONBytes(fileDataList.get(i).get("bytes")); String entryName = (String) fileDataList.get(i).get("fileName"); ZipEntry zipEntry = new ZipEntry(entryName); zipOut.putNextEntry(zipEntry); zipOut.write(fileData); zipOut.closeEntry(); } zipOut.flush(); zipOut.close(); baos.flush(); // 设置HTTP响应头 response.setContentType("application/zip"); String fileName = String.format("%s_%s_全病案_%s.zip", province, name, DateUtil.format(new Date(), "yyyyMMdd")); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); // 将zip数据写入响应流 IoUtil.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); }

本文作者:Weee

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!