天天看點

zip壓縮,使用org.apache.tools.zip實作zip壓縮和解壓

1、使用apache的ant解壓

org.apache.tools.zip

2、引入pom

<!-- https://mvnrepository.com/artifact/org.apache.ant/ant -->
    <dependency>
      <groupId>org.apache.ant</groupId>
      <artifactId>ant</artifactId>
      <version>1.10.5</version>
    </dependency>

           
package com.study.zip;

import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

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

/**
 * 
 */
public class ZipUtilApache {
    private static final int buffer = 2048;


    /**
     * 解壓zip
     *
     * @param zipPath      zip檔案路徑 必傳
     * @param saveFilePath 如果為空那麼解壓到zipPath的目前目錄,不為空解壓到指定目錄
     */
    public static void unZip(String zipPath, String saveFilePath) {
        int count = -1;
        String savepath = "";
        File file = null;
        InputStream is = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        //儲存解壓檔案目錄
        if (StringUtils.isNotBlank(saveFilePath)) {
            savepath = new File(saveFilePath) + File.separator;
        } else {
            savepath = new File(zipPath).getParent() + File.separator;
        }
        new File(savepath).mkdir(); //建立儲存目錄
        ZipFile zipFile = null;
        try {
            //解決中文亂碼問題  格式有GBK  UTF8
            zipFile = new ZipFile(zipPath, "GBK");
            Enumeration<?> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                byte buf[] = new byte[buffer];
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String filename = entry.getName();
                boolean ismkdir = false;
                //檢查此檔案是否帶有檔案夾
                if (filename.lastIndexOf("/") != -1) {
                    ismkdir = true;
                }
                filename = savepath + filename;
                //如果是檔案夾先建立
                if (entry.isDirectory()) {
                    file = new File(filename);
                    file.mkdirs();
                    continue;
                }
                file = new File(filename);
                if (!file.exists()) {
                    //如果是目錄先建立
                    if (ismkdir) {
                        //目錄先建立
                        new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs();
                    }
                }
                //建立檔案
                file.createNewFile();
                is = zipFile.getInputStream(entry);
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos, buffer);
                while ((count = is.read(buf)) > -1) {
                    bos.write(buf, 0, count);
                }
                bos.flush();
                bos.close();
                fos.close();
                is.close();
            }
            zipFile.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (zipFile != null) {
                    zipFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 壓縮檔案
     * @param sourceDir 原檔案目錄
     * @param zipFile 壓縮後的檔案名稱
     * @dirFlag zip檔案中第一層是否包含一級目錄,true包含;false沒有
     * @throws Exception
     */
    public static void doZip(String sourceDir, String zipFile,boolean dirFlag) throws Exception{
        OutputStream os= new FileOutputStream(new File(zipFile));
        BufferedOutputStream bos = new BufferedOutputStream(os);
        ZipOutputStream zos = new ZipOutputStream(bos);
        File file = new File(sourceDir);
        String basePath = null;
        if (file.isDirectory()) {
            basePath = file.getPath();
        } else {
            basePath = file.getParent();
        }
        zipFile(file, basePath, zos,dirFlag);
        zos.closeEntry();
        zos.close();
    }

    /**
     * 壓縮檔案
     * @param source
     * @param basePath
     * @param zos
     * @param dirFlag  zip檔案中第一層是否包含一級目錄,true包含;false沒有
     * @throws Exception
     */
    private static void zipFile(File source, String basePath, ZipOutputStream zos, boolean dirFlag) throws Exception {
        File[] files = new File[0];
        if (source.isDirectory()) {
            files = source.listFiles();
        } else {
            files = new File[1];
            files[0] = source;
        }
        File basePathFile = new File(basePath);
        String directoryName = basePathFile.getName();
        String pathName;
        byte[] buf = new byte[1024];
        int length = 0;
        for (File file : files) {
            if (file.isDirectory()) {
                pathName = file.getPath().substring(basePath.length() + 1)+ "/";
                if (dirFlag) {
                    pathName = directoryName + File.separator + pathName;
                }
                zos.putNextEntry(new ZipEntry(pathName));
                zipFile(file, basePath, zos, dirFlag);
            } else {
                pathName = file.getPath().substring(basePath.length() + 1);
                if (dirFlag) {
                    pathName = directoryName + File.separator + pathName;
                }
                InputStream is = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(is);
                zos.putNextEntry(new ZipEntry(pathName));
                while ((length = bis.read(buf)) > 0) {
                    zos.write(buf, 0, length);
                }
                is.close();
            }
        }
    }

    public static void main(String[] args) throws Exception {
       // doZip("D:\\test\\b", "D:\\test\\10.zip",false);
       // doZip("D:\\test\\a", "D:\\test\\a.zip",false);

       // unZip("D:/test/ffff.zip",null);

        unZip("D:/test/a.zip", "D:/test/ccc");
    }
}