[英]Creating zip file in memory out of byte[]. Zip file is never suggest to download
[英]Creating zip file in memory out of byte[]. Zip file is allways corrupted
我的创建的zip文件有问题。 我正在使用Java 7.我尝试用字节数组创建一个zip文件,其中包含两个或更多Excel文件。 应用程序完成,无任何例外。 所以,我认为一切都很好。 在我尝试打开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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.