在写入以下代码时,我得到无效的 zip:
public static byte[] zip(final Map<String, byte[]> mapReports) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Map.Entry<String, byte[]> report : mapReports.entrySet()) {
ZipEntry entry = new ZipEntry(report.getKey());
zos.putNextEntry(entry);
zos.write(report.getValue());
zos.closeEntry();
}
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException("Exception zipping files", e);
}
}
我将其写入文件的方式是:
byte[] zip = zip(mapReports);
File file = new File("demo.zip");
try {
OutputStream os = new FileOutputStream(file);
os.write(zip);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
我做错了什么?
最佳答案
在调用 baos 之前,您需要
.close()
或 finish()
ZipOutputStream
流 .toByteArray()
由于 ByteArrayOutputStream
不需要关闭,和/或即使在关闭后您也可以调用 toByteArray()
,所以我建议您将其移到 try
block 之外:
public static byte[] zip(final Map<String, byte[]> mapReports) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Map.Entry<String, byte[]> report : mapReports.entrySet()) {
zos.putNextEntry(new ZipEntry(report.getKey()));
zos.write(report.getValue());
}
} catch (Exception e) {
throw new RuntimeException("Exception zipping files", e);
}
return baos.toByteArray();
}
关于java - 使用 ZipOutputStream 压缩时 zip 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60818315/