我的创建的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)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
它必须是一个非常简单的失败,但我找不到它.如果你可以帮我解决我的问题会很好.非常感谢提前.
Ian*_*rts 16
您在关闭之前将其转换ByteArrayOutputStream为a .您必须确保在执行之前关闭,这是确保这是一个try-with-resources构造的最简单方法:byte[]ZipOutputStreamzosbaos.toByteArray()
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
Run Code Online (Sandbox Code Playgroud)