import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* ZIP压缩工具类
*/
public class ZipUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ZipUtil.class);
private final static String FILE_TYPE = ".zip";
public static void main(String[] args) {
String filePath = "D:\\PPT课件\\01-课程简介";
ZipUtil.compress(filePath, filePath);
}
/**
* 压缩文件
*
* @param srcFilePath 压缩源路径
* @param destFilePath 压缩目的路径
*/
public static File compress(String srcFilePath, String destFilePath) {
destFilePath = destFilePath + FILE_TYPE;
File src = new File(srcFilePath);
if (!src.exists()) {
throw new RuntimeException(srcFilePath + "不存在");
}
File zipFile = new File(destFilePath);
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
String baseDir = "";
compressbyType(src, zos, baseDir);
} catch (Exception e) {
LOGGER.error("压缩文件异常", e);
}
return zipFile;
}
/**
* 按照原路径的类型就行压缩。文件路径直接把文件压缩,
*
* @param src
* @param zos
* @param baseDir
*/
private static void compressbyType(File src, ZipOutputStream zos, String baseDir) {
if (!src.exists()) {
return;
}
LOGGER.info("压缩路径" + baseDir + src.getName());
//判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
if (src.isFile()) {
//src是文件,调用此方法
compressFile(src, zos, baseDir);
} else if (src.isDirectory()) {
//src是文件夹,调用此方法
compressDir(src, zos, baseDir);
}
}
/**
* 压缩文件
*/
private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
if (!file.exists()) {
return;
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
ZipEntry entry = new ZipEntry(baseDir + file.getName());
zos.putNextEntry(entry);
int count;
byte[] buf = new byte[1024];
while ((count = bis.read(buf)) != -1) {
zos.write(buf, 0, count);
}
} catch (Exception e) {
LOGGER.error("压缩文件异常", e);
}
}
/**
* 压缩文件夹
*/
private static void compressDir(File dir, ZipOutputStream zos, String baseDir) {
if (!dir.exists()) {
return;
}
File[] files = dir.listFiles();
if (files.length == 0) {
try {
zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} catch (IOException e) {
LOGGER.error("压缩文件夹异常", e);
}
}
for (File file : files) {
compressbyType(file, zos, baseDir + dir.getName() + File.separator);
}
}
}
02-28
2506
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交