Java解压和压缩(zip格式)

spring boot项目中

将文件夹压缩成ZIP。

并且解压zip文件。



import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.zip.*;

public class ZipFileUtil {
    private static Logger logger = LoggerFactory.getLogger(ZipFileUtil.class);


    /**
     * 压缩 zip
     * @param filePath  文件夹 全路径
     * @param fileName  文件夹名称
     * @param outPath   压缩文件保存路径
     */
    public static void zipFile(String filePath, String fileName, String outPath) {
        logger.info("filePath:{}, fileName:{}, outPath:{}", filePath, fileName, outPath);
        try {
            //创建Test.zip文件
            OutputStream is = new FileOutputStream(outPath);
            //检查输出流,采用CRC32算法,保证文件的一致性
            CheckedOutputStream cos = new CheckedOutputStream(is, new CRC32());
            //创建zip文件的输出流
            ZipOutputStream zos = new ZipOutputStream(cos);
            //需要压缩的文件或文件夹对象
            File file = new File(filePath);
            //压缩文件的具体实现函数
            zipFilePost(zos,file, fileName);
            zos.close();
            cos.close();
            is.close();
            logger.info("压缩完成");
        } catch (Exception e) {
            logger.error("压缩失败zipFile,Exception:" + e);
        }
    }

    /**
     * 压缩文件
     * @param zos       zip文件的输出流
     * @param file      需要压缩的文件或文件夹对象
     * @param fileName  需要压缩的文件夹名
     */
    private static void zipFilePost(ZipOutputStream zos, File file, String fileName){
        try{
            String path = file.getPath();
            String zosName = "";
            if(!StringUtils.isEmpty(path)){
                zosName = path.substring(path.indexOf(fileName));
            }
            File[] files = file.listFiles();
            if(file.isDirectory() && files != null && files.length > 0) {
                // 创建压缩文件的目录结构
                zos.putNextEntry(new ZipEntry(zosName + File.separator));
                for(File f : files) {
                    zipFilePost(zos, f, fileName);
                }
            } else {
                logger.info("正在压缩文件:{}",file.getName());
                // 创建压缩文件
                zos.putNextEntry(new ZipEntry(zosName));
                // 用字节方式读取源文件
                InputStream is = new FileInputStream(file.getPath());
                // 创建一个缓存区
                BufferedInputStream bis = new BufferedInputStream(is);
                // 字节数组,每次读取1024个字节
                byte [] b = new byte[1024];
                // 循环读取,边读边写
                while(bis.read(b)!=-1) {
                    // 写入压缩文件
                    zos.write(b);
                }
                //关闭流
                bis.close();
                is.close();
            }
        } catch (Exception e) {
            logger.error("压缩文件失败zipFilePost,Exception:" + e);
        }
    }


    /**
     * 解压
     * @param path 需解压的zip: /var/xxx.zip
     */
    public static void unzip(String path) throws Exception{
        File file = new File(path);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
        String parent = file.getParent();
        File fout ;
        ZipEntry entry;
        while (true){
            entry = zis.getNextEntry();
            if (entry == null) {
                break;
            }
            fout = new File(parent, entry.getName());
            if (entry.isDirectory()){
                if (!fout.exists()){
                    fout.mkdirs();
                }
            } else {
                if(".DS_Store".contains(fout.getName()) || "__MACOSX".contains(fout.getName())){
                    continue;
                }
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fout));
                int b;
                byte[] buffer = new byte[2048];
                while((b = zis.read(buffer))!= -1){
                    bos.write(buffer, 0, b);
                }
                bos.close();
            }
        }
        zis.close();
        logger.info("解压完成");
    }

    public static void main(String[] args) throws Exception {
        // 需压缩的路径,全路径
        String filePath = "/test/xx/20200727";
        // 需要压缩的文件夹名
        String fileName = "20200727";
        // 压缩完成后保存为xxx.zip文件
        String outPath = "/test/xx/20200727.zip";
        zipFile(filePath, fileName, outPath);
        unzip("/test/xx/job.zip");


    }
}

参考:

https://blog.csdn.net/qq_29323645/article/details/103202158?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-6.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-6.control

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值