java (7z,zip)压缩和解压

1 篇文章 0 订阅

1.引入jar包

<dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.20</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.0-alpha1</version>
        </dependency>
        <dependency>
            <groupId>org.tukaani</groupId>
            <artifactId>xz</artifactId>
            <version>1.8</version>
        </dependency>
    </dependencies>

2.创建压缩工具类CompressUtils

/**
 * 压缩文件
 */
@Slf4j
public class CompressUtils {

    /**
     * 7z压缩
     * @param inputFile 要压缩的目录
     * @param outputFile 压缩文件存放目录
     * @throws IOException
     */
    public static void compress7z(String inputFile,String outputFile) {
        File input = new File(inputFile);
        try (SevenZOutputFile out = new SevenZOutputFile(new File(outputFile))) {
            compression7z(out,input,null);
        }catch (Exception ex){
            log.error("compress7z error:",ex);
        }
    }

    /**
     * 7z压缩  递归压缩方法
     * @param out  输出流
     * @param input 输出流
     * @param name 带要压缩的目录的文件
     * @throws IOException
     */
    public static void compression7z(SevenZOutputFile out , File input, String name) throws IOException {
        //7z实体
        SevenZArchiveEntry entry ;
        String fileName = StringUtils.isNotBlank(name)?(name+ File.separator):"";
        //判断是否是目录
        if(input.isDirectory()){
            File[] flist = input.listFiles();
            if(flist.length == 0){
                entry = out.createArchiveEntry(input,fileName);
                out.putArchiveEntry(entry);
            }else{
                for(int i = 0; i < flist.length ;i++){
                    compression7z(out,flist[i],fileName+ flist[i].getName());
                }
            }
        //如果是文件写入
        }else{
            try (FileInputStream fos = new FileInputStream(input); BufferedInputStream bufferedInputStream = new BufferedInputStream(fos)) {
                entry = out.createArchiveEntry(input,name);
                out.putArchiveEntry(entry);
                int len = -1;
                byte[] buf = new byte[4096];
                while((len = bufferedInputStream.read(buf)) != -1){
                    out.write(buf,0,len);
                }
                out.closeArchiveEntry();
            }catch (Exception ex){
                log.error("compress7z error:",ex);
            }
        }
    }

    /**
     * zip压缩
     * @param inputFile 要压缩的文件或目录
     * @param outputFile 压缩后的文件存放目录
     */
    public static void compressZip(String inputFile,String outputFile) {
        try(ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(outputFile)));) {
            compressZip(out, new File(inputFile), null);
        }catch (Exception ex){
            log.error("compressZip error:" , ex);
        }
    }

    /**
     * zip压缩   递归压缩方法
     * @param out
     * @param in
     * @param name
     * @throws IOException
     */
    public static void compressZip(ZipOutputStream out,File in,String name) {
        try {
            if (in.isDirectory()) {
                File[] flist = in.listFiles();
                name = StringUtils.isBlank(name) ? "" : (name + File.separator);
                //空目录
                if (null == flist || flist.length == 0) {
                    out.putNextEntry(new ZipEntry(name));
                } else {
                    for (File file : flist) {
                        compressZip(out, file, name + file.getName());
                    }
                }
            } else {
                try(FileInputStream fileInputStream = new FileInputStream(in)) {
                    out.putNextEntry(new ZipEntry(name));
                    int size;
                    byte[] bytes = new byte[4096];
                    while ((size = fileInputStream.read(bytes)) != -1) {
                        out.write(bytes, 0, size);
                    }
                }
            }
        }catch (Exception ex){
            log.error("compressZip error:",ex);
        }
    }

}

4.创建解压工具类DecompressUtils

/**
 * 解压缩
 */
@Slf4j
public class DecompressUtils {
    /**
     * 解压7z
     * @param inputFile  压缩文件
     * @param outputFile  解压的目录
     */
    public static void decompress7z(String inputFile,String outputFile){

        try(SevenZFile sevenZFile = new SevenZFile(new File(inputFile))) {
            Iterator<SevenZArchiveEntry> iterator = sevenZFile.getEntries().iterator();
            while (iterator.hasNext()){
                SevenZArchiveEntry nextEntry = iterator.next();
                String name = nextEntry.getName();
                String outPath = outputFile + File.separator + name;
                if(outPath.lastIndexOf("\\") != -1){
                    File outPathFile = new File(outPath);
                    if(!outPathFile.getParentFile().exists()){
                        outPathFile.getParentFile().mkdirs();
                    }
                    if(!outPathFile.exists()){
                        outPathFile.createNewFile();
                    }
                }
                try(FileOutputStream outputStream = new FileOutputStream(outPath);
                InputStream inputStream = sevenZFile.getInputStream(nextEntry)) {
                    byte[] bytes = new byte[1024];
                    int size;
                    while ((size = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, size);
                    }
                }
            }
        } catch (IOException e) {
            log.error("decompress7z error:",e);
        }
    }

    /**
     * 解压zip文件
     * @param inpath
     * @param outpath
     */
    public static void decompressZip(String inpath ,String outpath){
        try {
            ZipFile zipFile = new ZipFile(inpath);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while(entries.hasMoreElements()){
                ZipEntry zipEntry = entries.nextElement();
                String name = zipEntry.getName();
                String outputPath = outpath + File.separator + name;
                if(outputPath.lastIndexOf("\\") != -1){
                    File file = new File(outputPath);
                    if(!file.getParentFile().exists()){
                        file.getParentFile().mkdirs();
                    }
                    if(!file.exists()){
                        file.createNewFile();
                    }
                }
                try(InputStream inputStream = zipFile.getInputStream(zipEntry);FileOutputStream fileOutputStream = new FileOutputStream(outputPath)) {
                    int size;
                    byte[] bytes = new byte[1024];
                    while ((size = inputStream.read(bytes)) != -1) {
                        fileOutputStream.write(bytes, 0, size);
                    }
                }
            }
        }catch (Exception ex){
            log.error("decompresszip error" ,ex);
        }
    }
}

4.测试程序

public static void main(String[] args) {
        CompressUtils.compress7z("F:\\download\\chrome","E:\\test\\download.7z");
        System.out.println("compress7z end");
        DecompressUtils.decompress7z("E:\\test\\download.7z","E:\\test\\7z");
        System.out.println("decompress7z end");
        CompressUtils.compressZip("F:\\download\\chrome","E:\\test\\download.zip");
        System.out.println("compresszip end");
        DecompressUtils.decompressZip("E:\\test\\download.zip","E:\\test\\zip");
        System.out.println("decompresszip end");
    }

5.还可使用hutool  jar包中的ZipUtils

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Java 中使用 7z 压缩,可以使用第三方库 SevenZipJBinding。以下是一个简单的示例代码: ```java import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.github.junrar.Archive; import com.github.junrar.exception.RarException; import com.github.junrar.impl.FileVolumeManager; import com.github.junrar.rarfile.FileHeader; import net.sf.sevenzipjbinding.ExtractOperationResult; import net.sf.sevenzipjbinding.ISevenZipInArchive; import net.sf.sevenzipjbinding.SevenZip; import net.sf.sevenzipjbinding.SevenZipException; import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; public class SevenZipUtils { private static final Logger LOGGER = LogManager.getLogger(SevenZipUtils.class); /** * 解压 7z 文件 * * @param srcFile * 压缩文件 * @param destDir * 目标目录 * @throws IOException * @throws SevenZipException */ public static void extract7z(File srcFile, File destDir) throws IOException, SevenZipException { LOGGER.info("Extracting {} to {}", srcFile, destDir); RandomAccessFileInStream inputStream = null; ISevenZipInArchive inArchive = null; try { inputStream = new RandomAccessFileInStream(srcFile.getAbsolutePath(), "r"); inArchive = SevenZip.openInArchive(null, inputStream); int numItems = inArchive.getNumberOfItems(); for (int i = 0; i < numItems; i++) { ExtractOperationResult result = null; String destFileName = null; do { if (result != null) { LOGGER.warn("Extracting {} failed, trying again", destFileName); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } destFileName = inArchive.getProperty(i, ISevenZipInArchive.NM_FILE_NAME); if (StringUtils.isBlank(destFileName)) { LOGGER.warn("File name is blank, using default"); destFileName = FilenameUtils.getBaseName(srcFile.getName()) + "." + FilenameUtils.getExtension(srcFile.getName()) + "." + i; } destFileName = FilenameUtils.separatorsToSystem(destFileName); File destFile = new File(destDir, destFileName); if (destFile.exists()) { FileUtils.forceDelete(destFile); } if (inArchive.getArchiveFormat() == net.sf.sevenzipjbinding.ArchiveFormat.RAR) { FileVolumeManager fileVolumeManager = new FileVolumeManager(srcFile); Archive archive = new Archive(fileVolumeManager); FileHeader fileHeader = archive.getFileHeaders().stream().filter(fh -> destFileName.equals(fh.getFileNameString())).findFirst().get(); result = inArchive.extractSlow(i, fileHeader.getFileNameW(), destFile.getParent(), fileHeader.isEncrypted()); } else { result = inArchive.extractSlow(i, destFile); } } while (result != ExtractOperationResult.OK); } } finally { IOUtils.closeQuietly(inArchive); IOUtils.closeQuietly(inputStream); } } } ``` 需要注意的是,SevenZipJBinding 依赖于 7-Zip 命令行工具,因此需要先安装 7-Zip 并将其添加到环境变量中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值