本地zip文件解压与压缩

引用:



java库学习之commons-compress实现zip包的压缩和解压_年糕coder的博客-CSDN博客

本地文件压缩zip

//path:需要压缩的文件路径地址    
//返回地址为:压缩后的文件地址
public String zipFile(String path) {
        int buffSize = 10 * 1024 * 1024;
        String resultPath = path + ".zip";
        int length;
        File file = new File(path);
        List<File> filesToArchive;
        if (file.isDirectory()) {
            filesToArchive = getAllFile(new File(path));
            length= path.length();
        } else {
            filesToArchive = Collections.singletonList(file);
            length = file.getParent().length()+1;
        }
        try (ArchiveOutputStream o = new ZipArchiveOutputStream(new File(resultPath))) {
            for (File f : filesToArchive) {
                ArchiveEntry entry = o.createArchiveEntry(f, f.getPath().substring(length));
                o.putArchiveEntry(entry);
                if (f.isFile()) {
                    try (InputStream i = Files.newInputStream(f.toPath())) {
                        IOUtils.copyBytes(i, o, buffSize);

                    }
                }
                o.closeArchiveEntry();
            }
        } catch (IOException e) {
            log.error(压缩zip失败);
        }
        return resultPath;
    }

本地zip文件解压

//path:需要解压的zip文件地址
//返回结果:解压后的文件地址
public String unzipFile(String path) {
        int buffSize = 10 * 1024 * 1024;
        String zipUrl = path.substring(0, path.lastIndexOf('.')) + "/";
        ArchiveEntry zipEntry;
        try (
                FileInputStream fis = new FileInputStream(path);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
                ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(bufferedInputStream,"GBK", true)) {
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                File file = new File(zipUrl, zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    boolean mkdirs = file.mkdirs();
                    if (!mkdirs) {
                        log.error("make dir fails, dir exists Chinese");
                    }
                } else {
                    FileOutputStream outPut = FileUtils.openOutputStream(file);
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outPut);
                    IOUtils.copyBytes(zipInputStream, bufferedOutputStream, buffSize);
                }
            }
        } catch (IOException e) {
            log.error("解压失败")
        }
        return zipUrl;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值