1.依赖
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.5</version>
</dependency>
2.压缩(到本地目录)代码
public void zip(String sourceFile, String targetZip) {
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(new File(targetZip));
zip.setEncoding("UTF-8");
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(new File(sourceFile));
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.解压文件
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();
}