代码语言:java复制
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 压缩包工具类
*
* @author xuyt
* @date 2020/12/31 10:32
*/
public class ZipUtil {
public static void compressZipfile(String sourceDir,String outputFile) throws IOException {
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile));
compressDirectoryToZipfile(sourceDir,sourceDir,zipFile);
IOUtils.closeQuietly(zipFile);
}
private static void compressDirectoryToZipfile(String rootDir,String sourceDir,ZipOutputStream out) throws IOException {
for (File file : new File(sourceDir).listFiles()) {
if (file.isDirectory()) {
//如果是一个空文件夹
if (file.listFiles().length == 0) {
ZipEntry zipEntry = new ZipEntry(sourceDir.replace(rootDir, "") file.getName() "/");
out.putNextEntry(zipEntry);
out.closeEntry();
} else {
compressDirectoryToZipfile(rootDir, sourceDir file.getName() File.separator, out);
}
} else {
FileInputStream in = new FileInputStream(sourceDir file.getName());
try {
ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") file.getName());
out.putNextEntry(entry);
IOUtils.copy(in, out);
}catch (IOException e){
e.printStackTrace();
}finally {
IOUtils.closeQuietly(in);
}
}
}
}
public static void main(String[] args) throws IOException {
ZipUtil.compressZipfile("D:\工作文档\培训管理系统-培训统计模块\f15cf5d6182b43848550df9d58581f45\",
"D:\工作文档\培训管理系统-培训统计模块\培训班材料.zip");
}
}