【发布时间】:2020-07-04 04:43:34
【问题描述】:
在写入以下代码时,我得到了无效的 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();
}
我做错了什么?
【问题讨论】:
-
使用 FileOutputStream 代替 ByteArrayOutputStream,基于 File 类型的第二个方法参数。如果您尝试将整个内容保存在内存中,那么当您拥有大量数据时,您的程序的性能将会下降。对于非常大量的数据,性能损失将是残酷的。
标签: java zipoutputstream