引入jar包
<!--压缩-->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.5</version>
</dependency>
java工具代码
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.*;
/**
* @author Maple
* 生成压缩文件 (zip,rar 格式)
*/
@Slf4j
public class CompressUtil {
/**
* @param sourcePath 要压缩的文件路径
* @param suffix 生成的格式后最(zip、rar)
*/
public static String generateFile(String sourcePath, String suffix) throws Exception {
File file = new File(sourcePath);
// 压缩文件的路径不存在
if (!file.exists()) {
throw new Exception("路径 " + sourcePath + " 不存在文件,无法进行压缩...");
}
// 用于存放压缩文件的文件夹
String generateFile = file.getParent() + File.separator +"CompressFile";
File compress = new File(generateFile);
// 如果文件夹不存在,进行创建
if( !compress.exists() ){
compress.mkdirs();
}
// 目的压缩文件
String generateFileName = compress.getAbsolutePath() + File.separator + "银领科技" + file.getName() + "." + suffix;
// 输入流 表示从一个源读取数据
// 输出流 表示向一个目标写入数据
// 输出流
FileOutputStream outputStream = new FileOutputStream(generateFileName);
// 压缩输出流
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream