美文网首页
java解压缩zip、rar

java解压缩zip、rar

作者: 莫生人 | 来源:发表于2021-12-08 00:00 被阅读0次

解压缩zip

1.使用hutool工具包中ZipUtil工具类

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.2</version>
</dependency>

使用比较简单,下面只是其中一种用法(当然还有其他的使用方法,请自行查看源码):

ZipUtil.unzip(f.getAbsolutePath(), Charset.forName("GBK"));

参数是压缩包路径和编码,使用GBK是为了解决中文解压缩乱码的问题,测试使用了其他字符集,解压缩后中文都是乱码。

2.使用zip4j工具包

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>2.9.1</version>
</dependency>

使用比hutool工具包稍复杂一点:

ZipFile zipFile = new ZipFile(f.getAbsolutePath());
zipFile.setCharset(Charset.forName("GBK"));
File zdir = new File(f.getAbsolutePath().substring(0, f.getAbsolutePath().indexOf(".")));
if (!zdir.isDirectory()) {
    zdir.mkdir();
}
try {
    zipFile.extractAll(zdir.getAbsolutePath());
} catch (ZipException e) {
    e.printStackTrace();
}

字符集同样使用GBK,否则解压后中文也是乱码。zipFile.extractAll是解压到指定文件夹。

解压缩rar

1.使用junrar工具包

<dependency>
    <groupId>com.github.junrar</groupId>
    <artifactId>junrar</artifactId>
    <version>7.4.0</version>
</dependency>

调用方式:

File zdir = new File(f.getAbsolutePath().substring(0, f.getAbsolutePath().indexOf(".")));
if (!zdir.isDirectory()) {
    zdir.mkdir();
}
try {
    Junrar.extract(f.getAbsolutePath(), zdir.getAbsolutePath());
} catch (IOException e) {
    e.printStackTrace();
} catch (RarException e) {
    e.printStackTrace();
}

运行测试,居然报错:

23:31:45.233 [main] WARN com.github.junrar.Archive - Support for rar version 5 is not yet implemented!
23:31:45.247 [main] WARN com.github.junrar.Archive - exception in archive constructor maybe file is encrypted, corrupt or support not yet implemented
com.github.junrar.exception.UnsupportedRarV5Exception: null

junrar不支持rar5的解压缩!!!我曹,无情!!!
继续百度一番,没有找到其他方案,晚上在简书上,努力翻找,找到了新的解决方案,如下!

2.使用sevenzipjbinding

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

原文作者说,某些情况,由于文件编码问题,可能会出现乱码的情况,但是API上没有参数可以设置编码。但个人示例测试暂时没有发现乱码问题,贴下示例代码:

try {
   // f -  压缩文件
   RandomAccessFile randomAccessFile = new RandomAccessFile(f.getAbsolutePath(), "r");
   IInArchive archive = SevenZip.openInArchive(ArchiveFormat.RAR5,  new RandomAccessFileInStream(randomAccessFile));
   // 解压文件路径
   File zdir = new File( f.getAbsolutePath().substring(0,  f.getAbsolutePath() .indexOf(".")));
   if (!zdir.isDirectory()) {
       zdir.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, zdir.getAbsolutePath()));
   archive.close();
   randomAccessFile.close();
} catch (FileNotFoundException | SevenZipException e) {
   e.printStackTrace();
} 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) {
        log.info("IOException while extracting " + filePath);
        } finally{
            try {
            if(fos != null){
            fos.flush();
            fos.close();
            }
        } catch (IOException e) {
            log.error("Could not close FileOutputStream", e);
        }
        }
        return data.length;
    };
    }

    @Override
    public void prepareOperation(ExtractAskMode extractAskMode) {

    }

    @Override
    public void setOperationResult(ExtractOperationResult extractOperationResult) {
    }
}

最后,有兴趣还可以看一下Apache的common-compress,http://commons.apache.org/proper/commons-compress/examples.html,也可以对很多类型的压缩文件进行操作,好像没有rar格式的!!!

相关文章

网友评论

      本文标题:java解压缩zip、rar

      本文链接:https://www.haomeiwen.com/subject/zndzxrtx.html