@Java 文件压缩 支持多级目录压缩
package ext.util;
import ext.casc.MyUtil;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class ZipCompress {
private static final Logger log = LoggerFactory.getLogger(UtilController.class);
private String zipFileName; // 目的地Zip文件
private String sourceFileName; //源文件(带压缩的文件或文件夹)
public ZipCompress(String zipFileName, String sourceFileName) {
this.zipFileName = zipFileName;
this.sourceFileName = sourceFileName;
}
public void zip() throws Exception {
long startTime = System.currentTimeMillis();
//File zipFile = new File(zipFileName);
log.debug("压缩中..." + sourceFileName);
//创建zip输出流
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
out.setEncoding("GBK");
//创建缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(out);
String encoding = MyUtil.getEncoding("测编码格式");
System.out.println("当前编码格式---" + encoding);
File sourceFile = new File(sourceFileName);
//调用函数
compress(out, sourceFile, sourceFile.getName());
bos.flush();
bos.close();
out.flush();
out.close();
long endTime = System.currentTimeMillis();
log.debug("压缩完成" + zipFileName + "---时间>" + (endTime - startTime)/1000 + "秒");
}
public void compress(ZipOutputStream out, File sourceFile, String base) throws Exception {
//如果路径为目录(文件夹)
if (sourceFile.isDirectory()) {
//取出文件夹中的文件(或子文件夹)
File[] flist = sourceFile.listFiles();
if (flist.length == 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
{
log.debug(base + "/");
out.putNextEntry(new ZipEntry(base + "/"));
} else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
{
for (int i = 0; i < flist.length; i++) {
compress(out, flist[i], base + "/" + flist[i].getName());
}
}
} else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
{
byte[] buf = new byte[1024];
out.putNextEntry(new ZipEntry(base));
FileInputStream fos = new FileInputStream(sourceFile);
BufferedInputStream bis = new BufferedInputStream(fos);
int tag;
//将源文件写入到zip文件中
while ((tag = bis.read(buf)) != -1) {
out.write(buf,0,tag);
}
bis.close();
fos.close();
}
}
/**
* 功能描述:
* 压缩指定目录(可以是多级文件夹)
*
* @auther: xtan
* @date: 2020/12/3 16:27
*/
public static void processZip(String zipFileName, String sourceFileName) {
ZipCompress zipCom = new ZipCompress(zipFileName, sourceFileName);
try {
zipCom.zip();
} catch (Exception e) {
e.printStackTrace();
}
}
}