文件解压专题-2:支持Gzip、Rar5、rar、7z、tar.gz、zip

这篇博客详细介绍了如何在Java中实现Gzip、Rar5、7z、tar.gz以及zip这五种常见压缩格式的解压操作,包括每个格式的具体解压步骤和实现要点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件解压专题:支持Gzip、Rar5、rar、7z、tar.gz、zip

Gzip解压

public class GzipUploadServiceImpl implements UploadService {
   
    @Override
    public boolean isOwn(FileType fileType) {
   
        return FileType.GZ == fileType;
    }

    @Override
    public void uploadFile(String targetPath, File file, int depth, boolean isReservedDir) throws IOException, RarException {
   
        if (file.getName().endsWith(TAR_GZ)) {
   
            new TarGzUploadServiceImpl().uploadFile(targetPath, file, depth, isReservedDir);
            return;
        }
        try (InputStream is = Files.newInputStream(file.toPath());
             GzipCompressorInputStream gzip = new GzipCompressorInputStream(is)) {
   
            // 获取文件名
            String fileName = gzip.getMetaData().getFilename();
            if (fileName == null) {
   
                String name = file.getName();
                fileName = name.substring(0, name.lastIndexOf(Constants.DOT));
                fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
            }
            File destFile = FileUtils.getFile(targetPath, fileName);
            FileUtils.copyInputStreamToFile(gzip, destFile);
        } finally {
   
            new ProjectUtils().deleteTemFile(file);
        }
    }
}

Rar5解压

public class Rar5UploadServiceImpl implements UploadService {
   

    @Override
    public boolean isOwn(FileType fileType) {
   
        return FileType.RAR5 == fileType;
    }

    @Override
    public void uploadFile(String targetPath, File file, int count, boolean isReservedDir) throws IOException, RarException {
   
        ProjectUtils projectUtils = new ProjectUtils();
        if (count == Constants.MAX_DEPTH) {
   
            projectUtils.deleteTemFile(file);
            return;
        }

        //解压缩至指定目录outDir
        ExtractCallback.unrar5(file.getCanonicalPath(), targetPath, isReservedDir, count);

        projectUtils.deleteTemFile(file);
    }
}

具体实现Rar5的解压

import com.github.junrar.exception.RarException;

import net.sf.sevenzipjbinding.ExtractAskMode;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.IArchiveExtractCallback;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值