引入POM
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.5</version>
</dependency>
代码实例
package com.example.demo.controller;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CompressUtil {
public static void generateFile(String path, String format) throws Exception {
File file = new File(path);
if (!file.exists()) {
throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
}
String generateFile = file.getParent() + File.separator + "CompressFile";
File compress = new File(generateFile);
if (!compress.exists()) {
compress.mkdirs();
}
String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + format;
FileOutputStream outputStream = new FileOutputStream(generateFileName);
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
generateFile(zipOutputStream, file, "");
System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
zipOutputStream.close();
}
private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {
if (file.isDirectory()) {
File[] files = file.listFiles();
out.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
for (int i = 0; i < files.length; i++) {
generateFile(out, files[i], dir + files[i].getName());
}
} else {
FileInputStream inputStream = new FileInputStream(file);
out.putNextEntry(new ZipEntry(dir));
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
inputStream.close();
}
}
public static void main(String[] args) {
String path = "D:\\study-project-1\\demo";
String format = "rar";
try {
generateFile(path, format);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}