解压zip、rar、gz格式文件

 rar解压版本:需要使用0.7,其他版本尝试了,不行,而且rar压缩的时候,也需要指定rar4,高版本不支持

        <!--解压rar压缩-->
        <dependency>
            <groupId>com.github.junrar</groupId>
            <artifactId>junrar</artifactId>
            <version>0.7</version>
        </dependency>
//路由方法    
private void fileUnCompressUtil(File file,String realPath, String randomFileName, String fileType) {
        String filePath = realPath + randomFileName;
        try {
            //解压.zip格式文件
            if (fileType == CompressType.ZIP.name()) {
                CompressUtils.unzip(filePath);
            }
            //rar格式解压,需要一个后缀名以.rar结尾的文件
            if (fileType == CompressType.RAR.name()) {
                CompressUtils.unPackRar(file,filePath.substring(0,filePath.lastIndexOf(".")));
            }
        } catch (ZipException e) {
            logger.error("解压异常:{}", filePath);
            CoreCommonUtils.raiseRuntimeException(e);
        }
    }

工具类:

/**
 * Qiangungun.com Inc.
 * <p/>
 * Copyright (c) 2014-2016 All Rights Reserved.
 */
package com.qiangungun.boss.web.common;


import com.github.junrar.Archive;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * CompressUtil.<br />
 *
 * Created by ghost on 2016/5/26.
 */
public class CompressUtils {

    private static final Logger logger = LoggerFactory.getLogger(CompressUtils.class);
    /**
     * 使用给定密码解压指定的ZIP压缩文件到指定目录
     * <p>
     * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
     * @param zip 指定的ZIP压缩文件
     * @param dest 解压目录
     * @param passwd ZIP文件的密码
     * @return 解压后文件数组
     * @throws ZipException 压缩文件有损坏或者解压缩失败抛出
     */
    public static File[] unzip(String zip, String dest, String passwd) throws ZipException {
        File zipFile = new File(zip);
        if(StringUtils.isEmpty(dest)){
            dest = zipFile.getParentFile().getAbsolutePath();
        }
        return unzip(zipFile, dest, passwd);
    }

    /**
     * 带加密的解压文件<br/>
     *
     * @param zip
     * @param passwd
     * @return
     * @throws ZipException
     */
    public static File[] unzip(String zip, String passwd) throws ZipException {
        return unzip(zip, zip.substring(0,zip.lastIndexOf("\\")), passwd);
    }

    /**
     * 直接解压文件<br/>
     *
     * @param zip
     * @return
     * @throws ZipException
     */
    public static File[] unzip(String zip) throws ZipException {
        return unzip(zip, null, null);
    }

    /**
     * 直接解压文件<br/>
     *
     * @param zip
     * @return
     * @throws ZipException
     */
    public static File[] unzip(File zip) throws ZipException {
        return unzip(zip, zip.getParentFile().getAbsolutePath(), null);
    }

    /**
     * 使用给定密码解压指定的ZIP压缩文件到指定目录
     * <p>
     * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
     * @param zipFile 指定的ZIP压缩文件
     * @param dest 解压目录
     * @param passwd ZIP文件的密码
     * @return  解压后文件数组
     * @throws ZipException 压缩文件有损坏或者解压缩失败抛出
     */
    public static File[] unzip(File zipFile, String dest, String passwd)throws ZipException {
        ZipFile zFile = new ZipFile(zipFile);
        zFile.setFileNameCharset("GBK");
        if (!zFile.isValidZipFile()) {
            throw new ZipException("压缩文件不合法,可能被损坏.");
        }
        dest = dest + "//" + zipFile.getName().substring(0,zipFile.getName().lastIndexOf("."));
        File destDir = new File(dest);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        if (zFile.isEncrypted()) {
            zFile.setPassword(passwd.toCharArray());
        }

        try {
            zFile.extractAll(dest);
        }catch (ZipException e){
            logger.error("解压文件错误,删除目录下的文件。",e);
            if(deleteDir(destDir)){
                logger.info("解压错误,删除目录成功。");
            }
            throw  e;
        }
        List<net.lingala.zip4j.model.FileHeader> headerList = zFile.getFileHeaders();
        List<File> extractedFileList = new ArrayList<File>();
        for(net.lingala.zip4j.model.FileHeader fileHeader : headerList) {
            if (!fileHeader.isDirectory()) {
                extractedFileList.add(new File(destDir,fileHeader.getFileName()));
            }
        }
        File[] extractedFiles = new File[extractedFileList.size()];
        extractedFileList.toArray(extractedFiles);
        return extractedFiles;
    }

    /**
     * 删除目录或文件下面的全部文件
     * @param destDir
     * @return
     */
    private static boolean deleteDir(File destDir) {
        if(destDir.isDirectory()){
            String[] childrens = destDir.list();
            if(null != childrens){
                for (String children : childrens){
                    deleteDir(new File(children));
                }
            }
        }
        destDir.delete();
        return true;
    }

    public static Boolean zipFiles(List<File> fileList, ZipFile zipFile, String password){
        logger.info("开始压缩文件:"+fileList.size());
        try {

            ArrayList<File> filesToAdd = new ArrayList<File>();
            for (File file :fileList){
                filesToAdd.add(file);
            }
            ZipParameters parameters = new ZipParameters();
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            parameters.setPassword(password);
            zipFile.addFiles(filesToAdd, parameters);
        } catch (ZipException e) {
          logger.error("压缩文件失败",e);
            return  false;
        }
        return  true;
    }

    public static Boolean zipFiles(List<File> fileList, ZipFile zipFile){
        logger.info("开始压缩文件:"+fileList.size());
        try {

            ArrayList<File> filesToAdd = new ArrayList<File>();
            for (File file :fileList){
                filesToAdd.add(file);
            }
            ZipParameters parameters = new ZipParameters();
            parameters.setEncryptFiles(false);
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            zipFile.addFiles(filesToAdd, parameters);
        } catch (ZipException e) {
            logger.error("压缩文件失败",e);
            return  false;
        }
        return  true;
    }

    public static File doGzipCompressFile(String inFileName) {

        try {

            logger.info("开始压缩文件gz");
            String outFileName = inFileName + ".gz";
            GZIPOutputStream out = null;
            try {
                out = new GZIPOutputStream(new FileOutputStream(outFileName));
            } catch(FileNotFoundException e) {
                logger.error("Could not create file"+outFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }

            FileInputStream in = null;
            try {
                in = new FileInputStream(inFileName);
            } catch (FileNotFoundException e) {
                logger.error("File not found. " + inFileName);
            }

            logger.info("Transfering bytes from input file to GZIP Format.");
            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();

            logger.info("Completing the GZIP file");
            out.finish();
            out.close();
            return new File(outFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File doUnGzipcompressFile(String gzip) {

        try {

            if (!getExtension(gzip).equalsIgnoreCase("gz")) {
                logger.error("File name must have extension of \".gz\"");
            }

            logger.info("Opening the compressed file.");
            GZIPInputStream in = null;
            try {
                in = new GZIPInputStream(new FileInputStream(gzip));
            } catch(FileNotFoundException e) {
                logger.error("File not found. " + gzip);
            }

            logger.info("Open the output file.");
            String outFileName = getFileName(gzip);
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(outFileName);
            } catch (FileNotFoundException e) {
                logger.error("Could not write to file. " + outFileName);
            }

            logger.info("Transfering bytes from compressed file to the output file.");
            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            logger.info("Closing the file and stream");
            in.close();
            out.close();

            return new File(outFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * rar文件解压(不支持有密码的压缩包)
     *
     * @param rarFile  rar压缩包
     * @param destPath 解压保存路径
     */
    public static void unPackRar(File rarFile, String destPath) {
        try (Archive archive = new Archive(rarFile)) {
            if (null != archive) {
                com.github.junrar.rarfile.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) {
            logger.error("unpack rar file fail....", e.getMessage(), e);
        }
    }


//    //解压.rar文件
//    public static void unRar(String sourceFile, String outputDir) throws Exception {
//        Archive archive = null;
//        FileOutputStream fos = null;
//        File file = new File(sourceFile);
//        try {
//            archive = new Archive(file);
//            com.github.junrar.rarfile.FileHeader fh = archive.nextFileHeader();
//            int count = 0;
//            File destFileName = null;
//            while (fh != null) {
//                System.out.println((++count) + ") " + fh.getFileNameString());
//                String compressFileName = fh.getFileNameString().trim();
//                destFileName = new File(outputDir + "/" + compressFileName);
//                if (fh.isDirectory()) {
//                    if (!destFileName.exists()) {
//                        destFileName.mkdirs();
//                    }
//                    fh = archive.nextFileHeader();
//                    continue;
//                }
//                if (!destFileName.getParentFile().exists()) {
//                    destFileName.getParentFile().mkdirs();
//                }
//                fos = new FileOutputStream(destFileName);
//                archive.extractFile(fh, fos);
//                fos.close();
//                fos = null;
//                fh = archive.nextFileHeader();
//            }
//
//            archive.close();
//            archive = null;
//        } catch (Exception e) {
//            throw e;
//        } finally {
//            if (fos != null) {
//                try {
//                    fos.close();
//                    fos = null;
//                } catch (Exception e) {
//                    //ignore
//                }
//            }
//            if (archive != null) {
//                try {
//                    archive.close();
//                    archive = null;
//                } catch (Exception e) {
//                    //ignore
//                }
//            }
//        }
//    }


    public static String getExtension(String f) {
        String ext = "";
        int i = f.lastIndexOf('.');

        if (i > 0 &&  i < f.length() - 1) {
            ext = f.substring(i+1);
        }
        return ext;
    }

    public static String getFileName(String f) {
        String fname = "";
        int i = f.lastIndexOf('.');

        if (i > 0 &&  i < f.length() - 1) {
            fname = f.substring(0,i);
        }
        return fname;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值