Java 解压 rar、zip、7z 等压缩包通用工具类

目录

问题

代码

pom

解压工具类

测试类


问题

项目中有一个需求,客户端上传压缩包到服务器,需要先解压压缩包,拿到文件后进一步业务处理(保存图片,导入excel表格中的数据等等)。

上传的压缩包有多种格式,可能是 rar 或者 zip,Java 自带的工具类只能解压 zip,rar 需要额外导入其他依赖来解压。

记录下当时项目中用来解压 rar 的代码,该工具类也可以解压 zip 7z 等压缩包。

代码

pom

        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding-all-platforms</artifactId>
            <version>16.02-2.01</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding</artifactId>
            <version>16.02-2.01</version>
        </dependency>

解压工具类

public class UnCompressUtil {
    private static final Logger logger = Logger.getLogger(UnCompressUtil.class.getCanonicalName());

    /**
     * 解压rar
     *
     * @param file rar
     * @param extractPath 解压路径
     */
    public static void unCompress(File file, String extractPath) {
        try{
            RandomAccessFile randomAccessFile = new RandomAccessFile(file.getAbsolutePath(), "r");
            IInArchive archive = SevenZip.openInArchive(null,  new RandomAccessFileInStream(randomAccessFile));
            // 解压⽂件路径
            File extractDir = new File(extractPath);
            if (!extractDir.isDirectory()) {
                extractDir.mkdir();
            }
            int[] in = new int[archive.getNumberOfItems()];
            for(int i=0;i<in.length;i++){
                in[i] = i;
            }
            archive.extract(in, false, new ExtractCallback(archive, extractDir.getAbsolutePath()));
            archive.close();
            randomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ExtractCallback implements IArchiveExtractCallback {
        private final IInArchive inArchive;

        private final String extractPath;

        public ExtractCallback(IInArchive inArchive, String extractPath) {
            this.inArchive = inArchive;
            if (!extractPath.endsWith("/") && !extractPath.endsWith("\\")) {
                extractPath += File.separator;
            }
            this.extractPath = extractPath;
        }

        @Override
        public void setTotal(long total) {

        }

        @Override
        public void setCompleted(long complete) {

        }

        @Override
        public ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException {
            return data -> {
                String filePath = inArchive.getStringProperty(index, PropID.PATH);
                FileOutputStream fos = null;
                try {
                    File path = new File(extractPath + filePath);

                    if(!path.getParentFile().exists()){
                        path.getParentFile().mkdirs();
                    }

                    if(!path.exists()){
                        path.createNewFile();
                    }
                    fos = new FileOutputStream(path, true);
                    fos.write(data);
                } catch (IOException e) {
                    logger.log(null, "IOException while extracting " + filePath);
                } finally{
                    try {
                        if(fos != null){
                            fos.flush();
                            fos.close();
                        }
                    } catch (IOException e) {
                        logger.log(null, "Could not close FileOutputStream", e);
                    }
                }
                return data.length;
            };
        }

        @Override
        public void prepareOperation(ExtractAskMode extractAskMode) {

        }

        @Override
        public void setOperationResult(ExtractOperationResult extractOperationResult) {
        }

    }
}

测试类

class UnCompressUtilTest {

    @Test
    void unCompress() {
        String rarPath = "C:\\Users\\XXX\\Desktop\\test.rar";
        File file = new File(rarPath);
        String extractPath = "C:\\Users\\XXX\\Desktop";
        UnCompressUtil.unCompress(file, extractPath);
    }
}

  • 21
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java语言可以使用Apache Commons Compress库来解压7-ZIP、ACE、ALZ、ZIPRAR、TAR、ZIPRAR格式压缩包。以下是一个示例代码: ```java import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; import org.apache.commons.compress.compressors.z.ZCompressorInputStream; import org.apache.commons.compress.utils.IOUtils; import java.io.*; public class Uncompressor { public static void main(String[] args) throws IOException, ArchiveException { File input = new File("compressed_file_path"); File outputDir = new File("output_directory_path"); try (InputStream inputStream = new FileInputStream(input); ArchiveInputStream archiveInputStream = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(inputStream))) { ArchiveEntry entry; while ((entry = archiveInputStream.getNextEntry()) != null) { File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.isDirectory() && !outputFile.mkdirs()) { throw new IOException("Failed to create directory " + outputFile); } } else { try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) { IOUtils.copy(archiveInputStream, outputStream); } } } } } } ``` 该示例代码可以处理多种压缩包格式,如ZIPRAR、TAR、GZIP、BZIP2、XZ和Z。你可以根据自己的需要选择要解压压缩包格式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值