部分代码:
String zipFile :将要压缩成的文件位置 “地址/name.zip”
String zipFrontFile : 将要压缩成的文件名称 “name.zip”
List srcfile : 要压缩的文件集合
HttpServletResponse response : 请求的响应
try{
byte[] buf = new byte[2048];
// 创建值班单zip文件
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
// 循环压缩文件
for (int i = 0; i < srcfile.size(); i++) {
File file = srcfile.get(i);
FileInputStream in = new FileInputStream(file);
// 添加压缩包文件
out.putNextEntry(new ZipEntry(file.getName()));
int len = 0;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// 关闭入口
out.closeEntry();
// 关闭文件流
in.close();
}
// 关闭文件流
out.close();
// 写出文件到前台
InputStream ins = new FileInputStream(zipFile);
// 放到缓冲流里面
BufferedInputStream bins = new BufferedInputStream(ins);
// 获取文件输出IO流
OutputStream outs = response.getOutputStream();
BufferedOutputStream bouts = new BufferedOutputStream(outs);
// 设置response内容的类型
response.setContentType("application/x-download");
response.setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode(zipFrontFile, "UTF-8"));
int bytesRead = 0;
byte[] buffer1 = new byte[2048];
// 开始向网络传输文件流
while ((bytesRead = bins.read(buffer1, 0, 2048)) > 0) {
bouts.write(buffer1, 0, bytesRead);
}
bouts.flush();
ins.close();
bins.close();
outs.close();
bouts.close();
} catch (Exception e) {
// logger.error("异常", e);
} finally {
// 删除zip和文件及删除目录
ToolUtils.deleteFiles(fileDirPath);
}
}
/** *删除zip和文件及删除目录 */
public static boolean deleteFiles(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
file.delete();
return true;
}
String[] fileList = file.list();
File temFile = null;
for (int i = 0; i < fileList.length; i++) {
if (path.endsWith(File.separator)) {
temFile = new File(path + fileList[i]);
} else {
temFile = new File(path + File.separator + fileList[i]);
}
if (temFile.isFile()) {
temFile.delete();
}
}
file.delete();
return flag;
}