我正在尝试使用ZIP捆绑文件并通过servlet返回ZIP。如果我只有一个文件,但是当我尝试添加更多文件时,它似乎只是被附加到第一个ZipEntry,因此zip存档被破坏了。
private void writeZipResponse(HttpServletResponse response,
List<File> bundle) {
try {
ByteArrayOutputStream bout=new ByteArrayOutputStream();
ZipOutputStream zout = new ZipOutputStream(bout);
ServletOutputStream out =response.getOutputStream();
for (File file : bundle) {
FileInputStream fi = new FileInputStream(file);
byte bytes[] = new byte[(int)file.length()];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=fi.read(bytes, offset, bytes.length-offset)) >= 0)
{ offset += numRead; }
// Ensure all the bytes have been read in
if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); }
fi.close();
ZipEntry zipEntry = new ZipEntry(file.getName());
//zipEntry.setCompressedSize(file.length());
zipEntry.setSize(offset);
CRC32 crc = new CRC32();
crc.update(bytes);
zipEntry.setCrc(crc.getValue());
zout.putNextEntry(zipEntry);
zout.write(bytes, 0, offset);
zout.closeEntry();
zout.finish();
fi.close();
}
zout.close();
response.setContentType("application/zip");
response.setHeader("Content-Disposition",
"attachment; filename=hivseqdb.zip;");
out.write(bout.toByteArray());
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:1)
你需要移动zout.finish();循环外的线。