Java多文件压缩下载示例代码
public void downForZip(HttpServletRequest req, HttpServletResponse response,List<SysAttachment> fileInfoList) {
File zipFile = null;
FileInputStream fis = null;
BufferedInputStream buff = null;
try {
zipFile = File.createTempFile("批量下载", ".zip");
FileOutputStream fot = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fot, new Adler32());
ZipOutputStream zos = new ZipOutputStream(cos);
int n = 1;
for (SysAttachment file: fileInfoList) {
InputStream inputStream = billFileService.getFileInputStream(file.getPath());
if (null == inputStream) {
break;
}
zos.putNextEntry(new ZipEntry(file.getName() + "(" + n + ")." + file.getSuffix()));
n++;
int bytesRead = 0;
while ((bytesRead = inputStream.read()) != -1) {
zos.write(bytesRead);
}
inputStream.close();
zos.closeEntry();
}
zos.close();
ServletOutputStream os = response.getOutputStream();
response.setCharacterEncoding("GB2312");
response.setContentType(req.getSession().getServletContext().getMimeType(zipFile.getName()));
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("批量下载.zip", "UTF-8"));
fis = new FileInputStream(zipFile);
buff = new BufferedInputStream(fis);
FileCopyUtils.copy(buff, os);
} catch (Exception e1) {
throw new BusinessException("批量下载失败");
} finally {
try {
if (null != fis) {
fis.close();
}
if (null != buff) {
buff.close();
}
} catch (IOException e) {
logger.error( "流关闭异常");
}
if (null != zipFile) {
zipFile.delete();
}
}
}