简体   繁体   English

JAVA - 使用 ZipOutptuStream 和 FileInputStream 损坏 ZIP 文件

[英]JAVA - Corrupt ZIP file using ZipOutptuStream with FileInputStream

Why might the following code be generating a corrupt zip file when output over a servlet output stream?为什么以下代码在通过 servlet 输出流输出时会生成损坏的 zip 文件? When writing the ZIP to disk locally using a FileOutputStream, the output stream does not appear to be corrupt.使用 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);

Is this perhaps an issue with order of flushing/closing streams?这可能是刷新/关闭流顺序的问题吗?

Try closing the zip entry before flushing the zip stream在刷新 zip 流之前尝试关闭 zip 条目

// close entry
zos.closeEntry();

zos.flush();

On the coding style, use try-with-resources to make sure the resources are closed properly.在编码风格上,使用try-with-resources来确保资源被正确关闭。

A potential problem I see is that the individual entries to be zipped are not unique.我看到的一个潜在问题是要压缩的单个条目不是唯一的。 If you are looping through in this code, forZip.getName() may have duplicates.如果您在此代码中循环,则forZip.getName()可能有重复项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM