直接上代码
public void exportTemplateZip(HttpServletResponse response, HttpServletRequest request) throws Exception{
//获取项目的路径
String path = this.getClass().getClassLoader().getResource("").getPath();
//两个需要压缩在一起的文件路径
String path1 = path+"template/" + "a.xlsx";
String path2 = path+"template/" + "b.xlsx";
File file1 = new File(path1);
File file2 = new File(path2);
File[] fileArray = new File[2];
fileArray[0] =file1;
fileArray[1] =file2;
//创建压缩文件
File zip = new File("template.zip");
//执行压缩(将上述两个文件写到压缩文件)
FileUtil.ZipFiles(fileArray, zip);
//把压缩文件读到缓存中
InputStream fis = new BufferedInputStream(new FileInputStream(zip));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");
String codedFileName = java.net.URLEncoder.encode("压缩文件.zip", "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + codedFileName);
OutputStream out = new BufferedOutputStream(response.getOutputStream());
//写文件到浏览器
out.write(buffer);
out.flush();
out.close();
//删除压缩文件
zip.delete();
}
//执行压缩的方法
public static void ZipFiles(java.io.File[] srcfile, java.io.File zipfile) {
byte[] buf = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipfile));
for (int i = 0; i < srcfile.length; i++) {
FileInputStream in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}