Java 工具类 - Zip压缩解压

注意:此类中用到的压缩类ZipEntry等都来自于org.apache.tools包而非java.util包
依赖:ant-1.7.1.jar

package com.tgb.hz.file;

import com.tgb.hz.common.ArrayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Enumeration;

/**
 * <p>zip 工具类</p> 
 *
 * <p>注意:此类中用到的压缩类ZipEntry等都来自于org.apache.tools包而非java.util包</p>
 * <p>依赖:ant-1.7.1.jar</p> 
 * 
 * @author hezhao
 * @Time   2017年7月28日 下午3:23:41
 */
public class ZipUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class);
    
    /** 
     * 使用GBK编码可以避免压缩中文文件名乱码 
     */  
    private static final String CHINESE_CHARSET = "GBK";  
      
    /** 
     * 文件读取缓冲区大小 
     */  
    private static final int CACHE_SIZE = 1024;
    
    private ZipUtil(){
        // 私用构造主法.因为此类是工具类.
    }

    /** 
     * <p> 
     * 压缩文件 
     * </p> 
     *  
     * @param sourceFolder 需压缩文件 或者 文件夹 路径
     * @param zipFilePath 压缩文件输出路径 
     * @throws Exception 
     */  
    public static void zip(String sourceFolder, String zipFilePath) throws Exception {  
        logger.debug("开始压缩 ["+sourceFolder+"] 到 ["+zipFilePath+"]");
        OutputStream out = new FileOutputStream(zipFilePath);  
        BufferedOutputStream bos = new BufferedOutputStream(out);  
        org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);  
        // 解决中文文件名乱码  
        zos.setEncoding(CHINESE_CHARSET);  
        File file = new File(sourceFolder);  
        String basePath = null;  
        if (file.isDirectory()) {  
            basePath = file.getPath();  
        } else {  
            basePath = file.getParent();  
        }  
        zipFile(file, basePath, zos);  
        zos.closeEntry();  
        zos.close();  
        bos.close();  
        out.close();  
        logger.debug("压缩 ["+sourceFolder+"] 完成!");
    }
    
    /** 
     * <p> 
     * 压缩文件 
     * </p> 
     *  
     * @param sourceFolders 一组 压缩文件夹 或 文件
     * @param zipFilePath 压缩文件输出路径 
     * @throws Exception 
     */  
    public static void zip(String[] sourceFolders, String zipFilePath) throws Exception {  
        OutputStream out = new FileOutputStream(zipFilePath);  
        BufferedOutputStream bos = new BufferedOutputStream(out);  
        org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);  
        // 解决中文文件名乱码  
        zos.setEncoding(CHINESE_CHARSET);  
        
        for (int i = 0; i < sourceFolders.length; i++) {
            logger.debug("开始压缩 ["+sourceFolders[i]+"] 到 ["+zipFilePath+"]");
            File file = new File(sourceFolders[i]);  
            String basePath = null;  
            basePath = file.getParent();  
            zipFile(file, basePath, zos);  
        }
        
        zos.closeEntry();  
        zos.close();  
        bos.close();  
        out.close();  
        logger.debug("压缩 "+ArrayUtil.join(sourceFolders)+" 完成!");
    }
      
    /** 
     * <p> 
     * 递归压缩文件 
     * </p> 
     *  
     * @param parentFile 
     * @param basePath 
     * @param zos 
     * @throws Exception 
     */  
    private static void zipFile(File parentFile, String basePath, org.apache.tools.zip.ZipOutputStream zos) throws Exception {  
        File[] files = new File[0];  
        if (parentFile.isDirectory()) {  
            files = parentFile.listFiles();  
        } else {  
            files = new File[1];  
            files[0] = parentFile;  
        }  
        String pathName;  
        InputStream is;  
        BufferedInputStream bis;  
        byte[] cache = new byte[CACHE_SIZE];  
        for (File file : files) {  
            if (file.isDirectory()) {  
                logger.debug("目录:"+file.getPath());
                
                basePath = basePath.replace('\\', '/');
                if(basePath.substring(basePath.length()-1).equals("/")){
                    pathName = file.getPath().substring(basePath.length()) + "/";  
                }else{
                    pathName = file.getPath().substring(basePath.length() + 1) + "/";  
                }
                
                zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));  
                zipFile(file, basePath, zos);  
            } else {  
                pathName = file.getPath().substring(basePath.length()) ;  
                pathName = pathName.replace('\\', '/');
                if(pathName.substring(0,1).equals("/")){
                    pathName = pathName.substring(1);
                }
                
                logger.debug("压缩:"+pathName);
                
                is = new FileInputStream(file);  
                bis = new BufferedInputStream(is);  
                zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));  
                int nRead = 0;  
                while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {  
                    zos.write(cache, 0, nRead);  
                }  
                bis.close();  
                is.close();  
            }  
        }  
    }  
      
    /**
     * 解压zip文件
     * 
     * @param zipFileName
     *            待解压的zip文件路径,例如:c:\\a.zip
     * 
     * @param outputDirectory
     *            解压目标文件夹,例如:c:\\a\
     */
    public static void unZip(String zipFileName, String outputDirectory)
            throws Exception {
        logger.debug("开始解压 ["+zipFileName+"] 到 ["+outputDirectory+"]");
        org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);

        try {

            Enumeration<?> e = zipFile.getEntries();

            org.apache.tools.zip.ZipEntry zipEntry = null;

            createDirectory(outputDirectory, "");

            while (e.hasMoreElements()) {

                zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();

                logger.debug("解压:" + zipEntry.getName());

                if (zipEntry.isDirectory()) {

                    String name = zipEntry.getName();

                    name = name.substring(0, name.length() - 1);

                    File f = new File(outputDirectory + File.separator + name);

                    f.mkdir();

                    logger.debug("创建目录:" + outputDirectory + File.separator + name);

                } else {

                    String fileName = zipEntry.getName();

                    fileName = fileName.replace('\\', '/');

                    if (fileName.indexOf("/") != -1) {

                        createDirectory(outputDirectory, fileName.substring(0,
                                fileName.lastIndexOf("/")));

                        fileName = fileName.substring(
                                fileName.lastIndexOf("/") + 1,
                                fileName.length());

                    }

                    File f = new File(outputDirectory + File.separator
                            + zipEntry.getName());

                    f.createNewFile();

                    InputStream in = zipFile.getInputStream(zipEntry);

                    FileOutputStream out = new FileOutputStream(f);

                    byte[] by = new byte[1024];

                    int c;

                    while ((c = in.read(by)) != -1) {

                        out.write(by, 0, c);

                    }

                    in.close();

                    out.close();

                }

            }
            logger.debug("解压 ["+zipFileName+"] 完成!");

        } catch (Exception ex) {

            System.out.println(ex.getMessage());

        } finally {
            zipFile.close();
        }

    }

    /**
     * 创建目录
     * @author hezhao
     * @Time   2017年7月28日 下午7:10:05
     * @param directory
     * @param subDirectory
     */
    private static void createDirectory(String directory, String subDirectory) {

        String dir[];

        File fl = new File(directory);

        try {

            if (subDirectory == "" && fl.exists() != true) {

                fl.mkdir();

            } else if (subDirectory != "") {

                dir = subDirectory.replace('\\', '/').split("/");

                for (int i = 0; i < dir.length; i++) {

                    File subFile = new File(directory + File.separator + dir[i]);

                    if (subFile.exists() == false)

                        subFile.mkdir();

                    directory += File.separator + dir[i];

                }

            }

        } catch (Exception ex) {

            System.out.println(ex.getMessage());

        }

    }  
    
    /**
     * 无需解压直接读取Zip文件和文件内容
     * @author hezhao
     * @Time   2017年7月28日 下午3:23:10
     * @param file 文件
     * @throws Exception
     */
    public static void readZipFile(String file) throws Exception {
        java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file);
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        java.util.zip.ZipInputStream zin = new java.util.zip.ZipInputStream(in);
        java.util.zip.ZipEntry ze;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                logger.info("file - " + ze.getName() + " : "
                        + ze.getSize() + " bytes");
                long size = ze.getSize();
                if (size > 0) {
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(zipFile.getInputStream(ze)));
                    String line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    br.close();
                }
                System.out.println();
            }
        }
        zin.closeEntry();
    }
    
    
    public static void main(String[] args) throws Exception {
        try {
//          readZipFile("D:\\new1\\文字.zip");
            
            //压缩文件
//          String sourceFolder = "D:/新建文本文档.txt";  
//          String zipFilePath = "D:/新建文本文档.zip";  
//          ZipUtil.zip(sourceFolder, zipFilePath);  
            
            //压缩文件夹
//          String sourceFolder = "D:/fsc1";  
//          String zipFilePath = "D:/fsc1.zip";  
//          ZipUtil.zip(sourceFolder, zipFilePath);  
            
            //压缩一组文件
//          String [] paths = {"D:/新建文本文档.txt","D:\\FastStoneCapturecn.zip","D:/new1"};
//          zip(paths, "D:/abc.zip");
            
//          unZip("D:\\FastStoneCapturecn.zip", "D:/fsc2");  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339

推荐阅读更多精彩内容

  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 3,833评论 2 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,546评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,705评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,226评论 25 707
  • 情人节由来之一 1、古罗马,一个早晨,士兵押着一个年青的教士走进鉴于,他目光炯炯,虔诚而智慧 2、狱长女儿双目失明...
    赵丽娟1974阅读 356评论 0 2