You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
2.0 KiB
67 lines
2.0 KiB
package com.platform.utils;
|
|
|
|
import java.io.File;
|
|
import java.io.FileInputStream;
|
|
import java.io.FileOutputStream;
|
|
import java.io.IOException;
|
|
|
|
import org.apache.log4j.Logger;
|
|
import org.apache.tools.zip.ZipEntry;
|
|
import org.apache.tools.zip.ZipOutputStream;
|
|
|
|
public class ZipCompressUtils {
|
|
private static Logger logger = Logger.getLogger(ZipCompressUtils.class);
|
|
|
|
public static void zip(File inputFile, String zipFileName) {
|
|
try {
|
|
// 解决中文文件夹名乱码的问题
|
|
FileOutputStream fos = new FileOutputStream(new String(zipFileName));
|
|
ZipOutputStream zos = new ZipOutputStream(fos); // 将文件输出流与zip输出流接起来
|
|
logger.info("压缩-->开始");
|
|
zip(zos, inputFile, "");
|
|
logger.info("压缩结束");
|
|
zos.close();
|
|
} catch (Exception e) {
|
|
// TODO: handle exception
|
|
}
|
|
}
|
|
|
|
public static void zip(ZipOutputStream zos, File file, String base) {
|
|
try {
|
|
// 如果句柄是文件夹
|
|
if (file.isDirectory()) {
|
|
File[] files = file.listFiles(); // 获取文件夹下的子文件或子目录
|
|
zos.putNextEntry(new ZipEntry(base + "/"));
|
|
logger.info("目录名:" + file.getName() + "|加入ZIP条目:" + base + "/");
|
|
base = (base.length() == 0 ? "" : base + "/");
|
|
// 遍历目录下的文件
|
|
for (int i = 0; i < files.length; i++) {
|
|
// 递归进入本方法
|
|
zip(zos, files[i], base + files[i].getName());
|
|
}
|
|
} else { // 如果句柄是文件
|
|
if (base == "")
|
|
base = file.getName();
|
|
zos.putNextEntry(new ZipEntry(base)); // 填入文件句柄
|
|
logger.info("文件名:" + file.getName() + "|加入ZIP条目:" + base);
|
|
// 开始压缩
|
|
// 从文件入流读,写入ZIP 出流
|
|
writeFile(zos, file);
|
|
}
|
|
} catch (Exception e) {
|
|
// TODO: handle exception
|
|
}
|
|
}
|
|
|
|
public static void writeFile(ZipOutputStream zos, File file)
|
|
throws IOException {
|
|
logger.info("开始压缩" + file.getName());
|
|
FileInputStream fis = new FileInputStream(file);
|
|
int len;
|
|
while ((len = fis.read()) != -1)
|
|
zos.write(len);
|
|
logger.info("压缩结束");
|
|
fis.close();
|
|
}
|
|
}
|