apache ant压缩到本地或者浏览器导出 以及解压

1.依赖

<dependency>
   <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.10.5</version>
</dependency>

2.压缩(到本地目录)代码

/**
 * 压缩
 *
 * @param sourceFile 压缩的源文件 如: c:/upload
 * @param targetZip  生成的目标文件 如:c:/upload.zip
 */
public void zip(String sourceFile, String targetZip) {
    Project prj = new Project();
    Zip zip = new Zip();
    zip.setProject(prj);
    zip.setDestFile(new File(targetZip));//设置生成的目标zip文件File对象
    //记得设置编码格式
    zip.setEncoding("UTF-8");
    FileSet fileSet = new FileSet();
    fileSet.setProject(prj);
    fileSet.setDir(new File(sourceFile));//设置将要进行压缩的源文件File对象
    //fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹,只压缩目录中的所有java文件
    //fileSet.setExcludes("**/*.java"); //排除哪些文件或文件夹,压缩所有的文件,排除java文件
    zip.addFileset(fileSet);
    zip.execute();
    System.out.println("正在压缩文件=================================");
}

3.浏览器导出

response.setHeader("Access-Control-Allow-Origin", "*");// 解决前端访问跨域问题
response.setContentType("application/octet-stream ");
response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
response.setHeader("Content-Disposition","attachment;filename=" + new String("批量导出.zip".getBytes("GB2312"), "ISO8859-1"));
response.setCharacterEncoding("UTF-8");

OutputStream out = response.getOutputStream();
File file = new File(path+"批量导出.zip");
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
out.write(buffer);
out.flush();
out.close();

4.解压文件

 /**
 * 解压
 *
 * @param zipPath         zip文件路径
 * @param destinationPath 解压的目的地点,不存在时会自动创建
 */
public static void unZip(String zipPath, String destinationPath) {
	File zipFile = new File(zipPath);
	if (!zipFile.exists()) {
		throw new RuntimeException(zipPath + " 不存在");
	}
	Project project = new Project();
	Expand expand = new Expand();
	expand.setProject(project);
	expand.setTaskType("unzip");
	expand.setTaskName("unzip");
	expand.setSrc(zipFile);
	expand.setDest(new File(destinationPath));
	expand.setEncoding(ENCODE);
	expand.execute();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值