java文件压缩并下载

直接上代码

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();
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值