java解压压缩包

java解压压缩包

在开发过程中,我们会遇到解压压缩包的情况。
废话少说,上代码:
首先是如何解压zip格式的压缩包文件:

/**
     * zip文件解压
     * @param destPath 解压文件路径
     * @param zipFile  压缩文件
     //* @param password 解压密码(如果有)
     */

    public static void unPackZip(File zipFile,String destPath) {

        try {
            ZipFile zip = new ZipFile(zipFile);

            /*zip4j默认用GBK编码去解压,这里设置编码为GBK的*/
            zip.setFileNameCharset("GBK");
            zip.extractAll(destPath);

            // 如果解压需要密码
//            if (zip.isEncrypted()) {
//                zip.setPassword(password);
//            }
        } catch (Exception e) {
        }
    }

那么rar格式的如何解压呢,代码如下:

/**
     * rar文件解压(不支持有密码的压缩包)
     *
     * @param rarFile  rar压缩包
     * @param destPath 解压保存路径
     */

    public static void unPackRar(File rarFile, String destPath) {
        try (Archive archive = new Archive(rarFile)) {
            if (null != archive) {
                FileHeader fileHeader = archive.nextFileHeader();
                File file = null;
                while (null != fileHeader) {
                    // 防止文件名中文乱码问题的处理
                    String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
                    if (fileHeader.isDirectory()) {
                        //是文件夹
                        file = new File(destPath + File.separator + fileName);
                        file.mkdirs();
                    } else {
                        //不是文件夹
                        file = new File(destPath + File.separator + fileName.trim());
                        if (!file.exists()) {
                            if (!file.getParentFile().exists()) {
                                // 相对路径可能多级,可能需要创建父目录.
                                file.getParentFile().mkdirs();
                            }
                            file.createNewFile();
                        }

                        FileOutputStream os = new FileOutputStream(file);
                        archive.extractFile(fileHeader, os);
                        os.close();
                    }

                    fileHeader = archive.nextFileHeader();
                }
            }
        } catch (Exception e) {
        }
    }

小伙伴们可以在前面进行压缩包格式的判断,运用不同的解压方法。
获取压缩包后缀名的方法如下:

//获得文件名称
        String fileName = file.getOriginalFilename();

        //获得文件后缀名
        String type = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值