【发布时间】:2017-01-05 18:30:14
【问题描述】:
为什么当通过 servlet 输出流输出时,以下代码会生成损坏的 zip 文件?使用 FileOutputStream 将 ZIP 写入本地磁盘时,输出流似乎没有损坏。
// Create zip stream
ZipOutputStream zos = new ZipOutputStream(this.servletOutputStream);
// prepare a new entry
ZipEntry zipEntry = new ZipEntry(forZip.getName());
zipEntry.setSize(forZip.getTotalSpace());
zipEntry.setTime(System.currentTimeMillis());
// write entry
zos.putNextEntry(zipEntry);
// write the file to the entry
FileInputStream toBeZippedInputStream = new FileInputStream(forZip);
IOUtils.copy(toBeZippedInputStream, zos);
zos.flush();
// close entry
zos.closeEntry();
// close the zip
zos.finish();
zos.close();
this.servletOutputStream.flush();
this.servletOutputStream.close();
// close output stream
IOUtils.closeQuietly(toBeZippedInputStream);
这可能是刷新/关闭流的顺序问题吗?
【问题讨论】:
-
您可能想刷新
toBeZippedInputStream而不是zos? -
您如何确定流数据已损坏?
-
您如何确定问题不在您未提供的代码中?如果是这段代码有问题,那么准备和提交minimal reproducible example 应该不会太难。
-
特别是,我的第一个猜测是在 Zip 数据之前将某些内容写入输出流。
-
您可能想了解what getTotalSpace() does。您应该完全删除该行;您不需要明确设置 ZipEntry 的大小。
标签: java servlets fileinputstream zipoutputstream