java解析压缩文件,支持zip,rar,7z压缩格式

最近项目有需求对压缩文件进行解析,需要支持市面上比较流行的压缩格式,诸如zip,rar,7z;

由于压缩文件解析比较常见,特将代码整理出来,供后续参考学习;

以下是java代码:

maven依赖:

		<!-- 解压rar -->
        <dependency>
            <groupId>com.github.junrar</groupId>
            <artifactId>junrar</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!-- 解压7z -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>org.tukaani</groupId>
            <artifactId>xz</artifactId>
            <version>1.5</version>
        </dependency>

压缩工具代码:

package xxx;

import com.github.junrar.Archive;
import com.github.junrar.UnrarCallback;
import com.github.junrar.rarfile.FileHeader;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * 解压文件
 * 支持 zip, rar, 7z
 * @author pansh
 * @since 2021-12-7 17:28:12
 */
public class UnZipUtils {

    public static final String PREFIX_PATH = "/opt/application/zip/";

    public static void main(String[] a) throws Exception {

//        un7z();

//        unzip();

        File srcFile = new File("C:\\Users\\pansh\\Desktop\\1.7z");
        FileInputStream fis = new FileInputStream(srcFile);
        copyZipFile(fis, "a.zip");

//        unrar(new CustomUnrarCallback());
    }

    /**
     * 获取随机数
     * @return
     */
    private static int getRandom () {
        Random r = new Random();
        return r.nextInt(10000);
    }

    /**
     * 复制压缩文件到本地
     * @param inputStream
     * @param fileName
     * @throws IOException
     */
    public static File copyZipFile (InputStream inputStream, String fileName) throws IOException {
        StringBuffer sb = new StringBuffer();
        long timeMillis = System.currentTimeMillis();
        String randomPath = sb.append(PREFIX_PATH).append(timeMillis).append("_").append(getRandom()).toString();
        File zipFile = new File(randomPath + File.separator + fileName);
        FileUtils.copyInputStreamToFile(inputStream, zipFile);
        return zipFile;
    }

    /**
     * 删除压缩文件
     * @param zipFile
     */
    public static void deleteZipFile (File zipFile) {
        if (zipFile.exists()) {
            zipFile.delete();
        }
    }

    /**
     * 解压7z文件 test
     */
    public static void un7z () throws Exception {
        File srcFile = new File("C:\\Users\\pansh\\Desktop\\2.7z");
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        long start = System.currentTimeMillis();
        SevenZFile zIn = new SevenZFile(srcFile);
        SevenZArchiveEntry entry;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {

                String path = entry.getName();
                System.out.println("path=" + path);

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
                InputStream inputStream = new ByteArrayInputStream(out.toByteArray());

                String[] pathArray = path.split("/");
                String fileName = pathArray[pathArray.length-1];
                System.out.println(fileName);

                File destFile = new File("C:\\Users\\pansh\\Desktop\\"+fileName);
                FileUtils.copyInputStreamToFile(inputStream, destFile);
                inputStream.close();

            }
        }

        zIn.close();
        long end = System.currentTimeMillis();
        System.out.println("解压"+srcFile.getName()+"耗时"+(end-start)+"毫秒");
    }

    /**
     * 解压rar文件 test
     */
    public static void unrar (UnrarCallback callback) throws Exception {
        File file = new File("C:\\Users\\pansh\\Desktop\\2.rar");
        Archive archive = new Archive(file, callback);
//        Archive archive = new Archive(new FileInputStream());
        if(archive == null){
            throw new FileNotFoundException("File NOT FOUND!");
        }
        if(archive.isEncrypted()){
            throw new Exception("File IS ENCRYPTED!");
        }
        List<FileHeader> files =  archive.getFileHeaders();
        for (FileHeader fh : files) {
            if(fh.isEncrypted()){
                throw new Exception("File IS ENCRYPTED!");
            }
            if (!fh.isDirectory()) {
                String path = fh.getFileNameString();
                System.out.println("path=" + path);
                InputStream inputStream = archive.getInputStream(fh);
                String[] pathArray = path.split("\\\\");
                String fileName = pathArray[pathArray.length-1];
                System.out.println(fileName);
                inputStream.close();
            }
        }
    }

    /**
     * 解压zip文件 test
     */
    public static void unzip () {
        File file = new File("C:\\Users\\pansh\\Desktop\\2.zip");
        ZipFile zipFile = null;
        ZipInputStream zin = null;
        FileInputStream fis = null;
        try {
            zipFile = new ZipFile(file);
            fis = new FileInputStream(file);
            zin = new ZipInputStream(fis);

            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                String path = ze.getName();
                System.out.println("path=" + path);
                if (!ze.isDirectory()) {
                    InputStream inputStream = zipFile.getInputStream(ze);
                    String[] pathArray = path.split("/");
                    String fileName = pathArray[pathArray.length-1];
                    System.out.println(fileName);
                    inputStream.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (zin != null) {
                    zin.closeEntry();
                    zin.close();
                }
                if (fis != null)
                    fis.close();
                if (zipFile != null)
                    zipFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

CustomUnrarCallback.java

package xxx;

import com.github.junrar.UnrarCallback;
import com.github.junrar.Volume;

/**
 * 自定义rar文件解压回调类
 * @author pansh
 * @since 2021-12-7 16:53:41
 */
public class CustomUnrarCallback implements UnrarCallback {

    @Override
    public boolean isNextVolumeReady(Volume volume) {
        return true;
    }

    @Override
    public void volumeProgressChanged(long l, long l1) {

    }
}

欢迎转载

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值