77 lines
2.1 KiB
Plaintext
77 lines
2.1 KiB
Plaintext
|
|
package com.bonus.core;
|
||
|
|
|
||
|
|
import java.io.*;
|
||
|
|
import org.apache.log4j.Logger;
|
||
|
|
import org.apache.tools.zip.ZipEntry;
|
||
|
|
import org.apache.tools.zip.ZipOutputStream;
|
||
|
|
|
||
|
|
public class ZipCompress {
|
||
|
|
|
||
|
|
private static Logger log = Logger.getLogger(ZipCompress.class);
|
||
|
|
|
||
|
|
public void zip(File inputFile, String zipFileName) {
|
||
|
|
try {
|
||
|
|
// 创建文件输出对象out,提示:注意中文支持
|
||
|
|
FileOutputStream out = new FileOutputStream(new String(zipFileName));
|
||
|
|
// 將文件輸出ZIP输出流接起来
|
||
|
|
ZipOutputStream zOut = new ZipOutputStream(out);
|
||
|
|
log.info("压缩-->开始");
|
||
|
|
zOut.setEncoding("gbk");
|
||
|
|
zip(zOut, inputFile, "");
|
||
|
|
|
||
|
|
log.info("压缩-->结束");
|
||
|
|
zOut.close();
|
||
|
|
|
||
|
|
} catch (Exception e) {
|
||
|
|
e.printStackTrace();
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
public static void zip(ZipOutputStream zOut, File file, String base) {
|
||
|
|
try {
|
||
|
|
|
||
|
|
// 如果文件句柄是目录
|
||
|
|
if (file.isDirectory()) {
|
||
|
|
// 获取目录下的文件
|
||
|
|
File[] listFiles = file.listFiles();
|
||
|
|
base = (base.length() == 0 ? "" : base + "/");
|
||
|
|
|
||
|
|
// 遍历目录下文件
|
||
|
|
for (int i = 0; i < listFiles.length; i++) {
|
||
|
|
// 递归进入本方法
|
||
|
|
zip(zOut, listFiles[i], base + listFiles[i].getName());
|
||
|
|
}
|
||
|
|
//file.delete();
|
||
|
|
}
|
||
|
|
// 如果文件句柄是文件
|
||
|
|
else {
|
||
|
|
if (base == "") {
|
||
|
|
base = file.getName();
|
||
|
|
}
|
||
|
|
// 填入文件句柄
|
||
|
|
zOut.putNextEntry(new ZipEntry(base));
|
||
|
|
log.info("文件名:" + file.getName() + "|加入ZIP条目:" + base);
|
||
|
|
|
||
|
|
// 开始压缩
|
||
|
|
// 从文件入流读,写入ZIP 出流
|
||
|
|
writeFile(zOut, file);
|
||
|
|
file.delete();
|
||
|
|
}
|
||
|
|
} catch (Exception e) {
|
||
|
|
e.printStackTrace();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
public static void writeFile(ZipOutputStream zOut, File file) throws IOException {
|
||
|
|
log.info("开始压缩" + file.getName());
|
||
|
|
FileInputStream in = new FileInputStream(file);
|
||
|
|
int len;
|
||
|
|
while ((len = in.read()) != -1)
|
||
|
|
zOut.write(len);
|
||
|
|
log.info("压缩结束" + file.getName());
|
||
|
|
in.close();
|
||
|
|
}
|
||
|
|
public static void main(String[] args) {
|
||
|
|
new ZipCompress().zip(new File("F://考试"), "F://考试.zip");
|
||
|
|
}
|
||
|
|
}
|