使用Java生成的ZIP压缩包解压失败是什么原因?
问题原因
你的ZIP生成代码存在两个核心问题:
- 每个文件内容写入完成后没有调用
zipOut.closeEntry()关闭当前压缩条目,不符合ZIP格式规范。 - 更关键的错误是:你在
try-with-resources代码块内部就返回了ByteArrayOutputStream的字节数组,此时ZipOutputStream还没有被自动关闭,ZIP文件必须的末尾中央目录索引结构还没写入输出流,最终生成的文件是不完整的,因此解压工具无法识别合法的ZIP格式。
修复方案
调整createZipArchive方法的返回时机,同时补充closeEntry调用即可:
public class ZipUtils { public static byte[] createZipArchive(Collection<FileWrapper> sourceFiles) throws IOException { var bytesOut = new ByteArrayOutputStream(); try (var zipOut = new ZipOutputStream(bytesOut)) { for (var sourceFile : sourceFiles) { try (var fileContent = sourceFile.getResource().getInputStream()) { var zipEntry = new ZipEntry(sourceFile.getFileName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fileContent.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } // 关闭当前压缩条目 zipOut.closeEntry(); } } zipOut.flush(); } // 等ZipOutputStream关闭、写入完整ZIP结构后再返回字节数组 return bytesOut.toByteArray(); } }
内容的提问来源于stack exchange,提问作者Antonio Dragos
相关产品推荐
相关产品推荐

