1、问题
用WinRAR软件无法解压用ZipOutputStream生成的zip压缩包,而用360压缩就可以解压
2、原因
流没有正常关闭
3、解决办法
可以使用try-with-resources来自动关闭ZipOutputStream
例:
public void compressedFile(String businessId, HttpServletResponse response) {try {// ... existing code ...// 创建ZipOutputStream对象,把它写入HTTP响应的输出流中(用try-with-resources 来自动关闭 ZipOutputStream,这里是重点,要关闭ZipOutputStream)try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {// ... existing code ...//压缩文件1byte[] file1Content = 获取文件byte;ZipEntry file1Entry = new ZipEntry("文件1");zipOutputStream.putNextEntry(file1Entry);//把文件写入zip输出流中zipOutputStream.write(file1Content);zipOutputStream.closeEntry();// ... existing code ...//压缩文件1byte[] file2Content = 获取文件byte;ZipEntry file2Entry = new ZipEntry("文件1");zipOutputStream.putNextEntry(file2Entry);//把文件写入zip输出流中zipOutputStream.write(file2Content);zipOutputStream.closeEntry();// ... existing code ...// 调用finish()方法来完成ZIP文件的写入(这里是重点,标记压缩已经完成)zipOutputStream.finish();} // ZipOutputStream 会在这里自动关闭// 刷新和关闭HttpServletResponse的输出流response.getOutputStream().flush();response.getOutputStream().close();} catch (Exception e) {logger.error(e.getMessage(), e);}}