Zip压缩和解压
最近遇到一个需求:
① 需要对指定目录压缩为 zip 文件
② 将指定路径下的 zip 文件解压到指定的路径下
对于工具,我一向的原则是用成熟的,能不自己写就别自己写,丑还问题多
看了下网上大多数的 zip 文件解压缩的实现方式看起来不是很理想,借用 Ant 可以简洁的实现该需求
话不多说,实现步骤如下:如有问题,欢迎指证
① 引入如下依赖
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>
② 代码如下
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import java.io.File;
import java.io.FileNotFoundException;
/**
* <em>.zip</em>类型文件工具类
*
* @author: yangbh29924
* @date: Dec 03, 2020
**/
@Slf4j
public class ZipUtils {
private ZipUtils() {
}
/**
* 将文件夹压缩为<em>.zip</em>类型的文件
*
* <p>将指定路径{@param srcPth}的文件夹压缩为名称为{@param deFileName}
* 的<em>.zip</em>格式的文件,后期可拓展的功能有:
* 1.对指定类型的文件排除
* 2.对指定类型的文件包含
*
* @param srcPth 目标文件夹
* @param desFileName 生成的zip包名称
* @return <em>.zip</em>格式的文件
* @throws FileNotFoundException
*/
public static File compressZip(String srcPth, String desFileName) throws Exception {
File srcDir = new File(srcPth);
File zipFile = new File(desFileName);
if (!srcDir.exists()) {
throw new FileNotFoundException("解析后的文件不存在!");
}
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcDir);
zip.addFileset(fileSet);
zip.execute();
return zipFile;
}
/**
* 对指定路径{@param zipFilepath}格式<em>.zip</em>的文件进行
* 解压到该路径下{@param destDir}
*
* @param zipFilepath <em>.zip</em>格式的文件路径
* @param destDir 解压后的文件路径
* @return File
*/
public static File unZip(String zipFilepath, String destDir) {
File dir = new File(destDir);
Project proj = new Project();
Expand expand = new Expand();
expand.setProject(proj);
expand.setTaskType("unzip");
expand.setTaskName("unzip");
expand.setEncoding("utf-8");
expand.setSrc(new File(zipFilepath));
expand.setDest(new File(destDir));
expand.execute();
return dir;
}
}
1662

被折叠的 条评论
为什么被折叠?



