创建环境==》引入相关依赖
<!-- https://mvnrepository.com/artifact/ant/ant --> ===》可以获取最新依赖
<!--zip-->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
使用方法 ==》文件定义
FileOutputStream fos1= new FileOutputStream(new File("aaaa.zip"));
// 或者
FileOutputStream fos1= new FileOutputStream(new File("aaaa.rar"));
//压缩文件
/*
* tmp: 需要压缩的路径(该文件是一个文件夹,也可以是文件)
* fos1: 提前定义好的文件路径(定义压缩包名(可以压缩为rar文件))
* Boolean :压缩文件格式,可以测试
*/
ReadZipFileUtils.toZip(tmp,fos1,false); // (不保留原结构)true会根据目录结构进行压缩
复制压缩工具方法
public class ReadZipFileUtils {
public static Logger LOG = LoggerFactory.getLogger(ReadZipFileUtils.class);
/**
* 实现文件夹压缩
* @param srcDir
* @param out
* @param KeepDirStructure
* @throws RuntimeException
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 定义方法
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean keepDirStructure) throws IOException {
byte[] buf = new byte[1024*10];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
} else {
//是文件夹
File[] listFiles = listFile(sourceFile.getAbsolutePath());
if(listFiles == null || listFiles.length == 0){
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if(keepDirStructure){
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name +File.separator));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
}else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (keepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + File.separator + file.getName(),keepDirStructure);
} else {
compress(file, zos, file.getName(),keepDirStructure);
}
}
}
}
}
// 可以自定义需要压缩的文件
private static File[] listFile(String path) {
return new File(path).listFiles((File file) ->
file.isFile()
&& file.getName().endsWith(".XLS"));
}
}