我创建的 zip 文件有问题。我正在使用 Java 7。我试图从字节数组创建一个 zip 文件,其中包含两个或多个 Excel 文件。该应用程序始终无一异常(exception)地完成。所以,我以为一切都好。在我尝试打开 zip 文件后,Windows 7 出现一条错误消息,提示 zip 文件可能已损坏。我无法打开它,我不知道为什么......! 我用谷歌搜索了这个问题,但我发现的代码片段看起来与我的实现完全一样。
这是我的代码:
if (repsList.size() > 1)
{
String today = DateUtilities.convertDateToString(new Date(), "dd_MM_yyyy");
String prefix = "recs_" + today;
String suffix = ".zip";
ByteArrayOutputStream baos = null;
ZipOutputStream zos = null;
try
{
baos = new ByteArrayOutputStream();
zos = new ZipOutputStream(baos);
for (RepBean rep : repsList)
{
String filename = rep.getFilename();
ZipEntry entry = new ZipEntry(filename);
entry.setSize(rep.getContent().length);
zos.putNextEntry(entry);
zos.write(rep.getContent());
zos.closeEntry();
}
// this is the zip file as byte[]
reportContent = baos.toByteArray();
}
catch (UnsupportedEncodingException e)
{
...
}
catch (ZipException e) {
...
}
catch (IOException e)
{
...
}
finally
{
try
{
if (zos != null)
{
zos.close();
}
if (baos != null)
{
baos.close();
}
}
catch (IOException e)
{
// Nothing to do ...
e.printStackTrace();
}
}
}
try
{
response.setContentLength(reportContent.length);
response.getOutputStream().write(reportContent);
}
catch (IOException e)
{
...
}
finally
{
try
{
response.getOutputStream().flush();
response.getOutputStream().close();
}
catch (IOException e)
{
...
}
}
这一定是一个非常简单的故障,但我找不到它。如果你能帮我解决我的问题,那就太好了。 非常感谢。
最佳答案
在关闭 ZipOutputStream
之前,您正在将 ByteArrayOutputStream
转换为 byte[]
。在执行 baos.toByteArray()
之前,您必须确保 zos
已关闭,确保这是一个 try-with-resources 构造的最简单方法:
try
{
try (baos = new ByteArrayOutputStream();
zos = new ZipOutputStream(baos))
{
for (RepBean rep : repsList)
{
String filename = rep.getFilename();
ZipEntry entry = new ZipEntry(filename);
entry.setSize(rep.getContent().length);
zos.putNextEntry(entry);
zos.write(rep.getContent());
zos.closeEntry();
}
}
// this is the zip file as byte[]
reportContent = baos.toByteArray();
}
// catch blocks as before, finally is no longer required as the try-with-resources
// will ensure the streams are closed
关于java - 在 byte[] 之外的内存中创建 zip 文件。 Zip 文件总是损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25974354/