0

为什么以下代码在通过 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);

这可能是刷新/关闭流的顺序问题吗?

4

2 回答 2

1

在刷新 zip 流之前尝试关闭 zip 条目

// close entry
zos.closeEntry();

zos.flush();

在编码风格上,使用try-with-resources确保资源正确关闭。

于 2017-01-05T18:48:28.763 回答
0

我看到的一个潜在问题是要压缩的各个条目不是唯一的。如果您在此代码中循环,forZip.getName()可能会有重复。

于 2020-02-19T15:04:29.603 回答