JAVA 压缩解压文件工具类(支持空文件压缩)

package com.xyebank.mobile.hb.file.util;

import lombok.extern.slf4j.Slf4j;

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

/**
 * zip解压示例
 *
 * @author : liufangli
 * @date : 20200309
 */
@Slf4j
public class ZipUtil {

    static int i = 0;
    public static void main(String[] args) throws Exception {
//        String filename = "/Users/apple/Desktop/hebaoFile/20191223/MPLCASH_22_888191100258387_PICKIMG_20191223.ZIP";
//        String path = "/Users/apple/Desktop/hebaoFile/b";
//        ZipUtil.unZip(filename, path);
       int a = ZipUtil.zip("/Users/apple/Desktop/hebaoFile/a/", "/Users/apple/Desktop/hebaoFile/g");
       System.out.println(a);
//        createNewzip("/Users/apple/Desktop/hebaoFile/b/f/","/Users/apple/Desktop/hebaoFile/d");
    }



    public static void unZip(String sourceFilename, String targetDir) throws IOException {
        unZip(new File(sourceFilename), targetDir);
    }

    /**
     * 将sourceFile解压到targetDir 支持空文件夹压缩
     *
     * @param sourceFile
     * @param targetDir
     * @throws RuntimeException
     */
    public static void unZip(File sourceFile, String targetDir) throws IOException {
        long start = System.currentTimeMillis();
        if (!sourceFile.exists()) {
            throw new FileNotFoundException("cannot find the file = " + sourceFile.getPath());
        }
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(sourceFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory()) {
                    String dirPath = targetDir + "/" + entry.getName();
                    createDirIfNotExist(dirPath);
                } else {
                    File targetFile = new File(targetDir + "/" + entry.getName());
                    createFileIfNotExist(targetFile);
                    InputStream is = null;
                    FileOutputStream fos = null;
                    try {
                        is = zipFile.getInputStream(entry);
                        fos = new FileOutputStream(targetFile);
                        int len;
                        byte[] buf = new byte[1024];
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                    } finally {
                        try {
                            fos.close();
                        } catch (Exception e) {
                            log.warn("close FileOutputStream exception", e);
                        }
                        try {
                            is.close();
                        } catch (Exception e) {
                            log.warn("close InputStream exception", e);
                        }
                    }
                }
            }
            log.info("解压完成,耗时:" + (System.currentTimeMillis() - start) + " ms");
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    log.warn("close zipFile exception ", e);
                }
            }
        }
    }

    public static void createDirIfNotExist(String path) {
        File file = new File(path);
        createDirIfNotExist(file);
    }

    public static void createDirIfNotExist(File file) {
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static void createFileIfNotExist(File file) throws IOException {
        createParentDirIfNotExist(file);
        file.createNewFile();
    }

//    public static void createParentDirIfNotExist(String filename){
//        File file = new File(filename);
//        createParentDirIfNotExist(file);
//    }

    public static void createParentDirIfNotExist(File file) {
        createDirIfNotExist(file.getParentFile());
    }


    private static final int BUFFER = 1024 * 10;

    /**
     * 将指定目录压缩到和该目录同名的zip文件,自定义压缩路径
     *
     * @param sourceFilePath 目标文件路径
     * @param zipFilePath    指定zip文件路径
     * @return
     */
    public static int zip(String sourceFilePath, String zipFilePath) throws FileNotFoundException {
//        boolean result = false;
        File source = new File(sourceFilePath);
  
        File zipFile = new File(zipFilePath + "/" + source.getName() + ".ZIP");
        if (zipFile.exists()) {
             log.info(zipFile.getName() + " is already exist.");
            return i;
        } else {
            if (!zipFile.getParentFile().exists()) {
                if (!zipFile.getParentFile().mkdirs()) {
                     log.info("cann't create file " + zipFile.getName());
                    return i;
                }
            }
        }
         log.info("creating zip file...");
        FileOutputStream dest = null;
        ZipOutputStream out = null;
        try {
            dest = new FileOutputStream(zipFile);
            CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
            out = new ZipOutputStream(new BufferedOutputStream(checksum));
            out.setMethod(ZipOutputStream.DEFLATED);
            i=0;
            compress(source, out, source.getName());
//            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (i>0) {
            log.info("done.");
        } else {
            log.info("fail.");
        }
        return i;
    }


    private static void compress(File file, ZipOutputStream out, String mainFileName) throws IOException {

        if (file.isFile()) {
            FileInputStream fi = null;
            BufferedInputStream origin = null;
            try {
                fi = new FileInputStream(file);
                origin = new BufferedInputStream(fi, BUFFER);
                int index = file.getAbsolutePath().indexOf(mainFileName);
                String entryName = file.getAbsolutePath().substring(index);
                i++;
                System.out.println(entryName);
                ZipEntry entry = new ZipEntry(entryName);
                out.putNextEntry(entry);
                byte[] data = new byte[BUFFER];
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (origin != null) {
                    try {
                        origin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (file.isDirectory()) {
            File[] fs = file.listFiles();
            if (fs != null && fs.length > 0) {
                for (File f : fs) {
                    compress(f, out, mainFileName);
                }
            }else{
                out.putNextEntry(new ZipEntry (mainFileName+File.separator));
            }
        }
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值