需要引入apache-ant-zip.jar包,简单封装的一个工具类可以直接用,还有升级空间
import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;
import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
/**
* @ Author :Kevin.
* @ Date :Created in 18:16 2018/12/25 0025
* @ Description:${description}
* @ Modified By:
* @Version: $version$
*/
public class FileCompressUtil {
private static final Logger logger=Logger.getLogger(FileCompressUtil.class);
/**
* 将文件压缩为zip格式
* @param sourcePath 文件路径
* @param zipPath 压缩包保存路径
* @param fileName 文件名称不带后缀
*/
public static boolean createZipFile(String sourcePath,String zipPath,String fileName){
String seperator=File.separator;
logger.info("文件路径格式:"+seperator);
File sourcefile=new File(sourcePath);
File zipFile=new File(zipPath+seperator+fileName+".zip");
if (!sourcefile.exists()){
logger.info("文件不存在:"+sourcefile.getName());
return false;
}
ZipOutputStream zos=null;
try {
zos=new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
//设置压缩包注释
// zos.setComment(comment);
//启用压缩
zos.setMethod(ZipOutputStream.DEFLATED);
//压缩级别为最强压缩,但时间要花得多一点
zos.setLevel(Deflater.BEST_COMPRESSION);
//设置压缩编码
zos.setEncoding("GBK");
//判断路径是否为目录
if (sourcefile.isFile()){//如果路径是文件,直接压缩
String zname=fileName