tar.gz文件解压缩

复制代码
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.zip.GZIPInputStream;

@Slf4j
@Component
public class TarGzExtractorJie {

    public static  void extractTarGzFile(String tarGzFilePath, String destinationFolder) {
        try {
            FileInputStream fileInputStream = new FileInputStream(tarGzFilePath);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            GZIPInputStream gzipInputStream = new GZIPInputStream(bufferedInputStream);
            TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzipInputStream);

            TarArchiveEntry entry;
            while ((entry = tarInputStream.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    new File(destinationFolder, entry.getName()).mkdirs();
                } else {
                    File outputFile = new File(destinationFolder, entry.getName());
                    File parentDirectory = outputFile.getParentFile();
                    if (!parentDirectory.exists()) {
                        parentDirectory.mkdirs();
                    }
                    OutputStream outputFileStream = new FileOutputStream(outputFile);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = tarInputStream.read(buffer)) != -1) {
                        outputFileStream.write(buffer, 0, length);
                    }
                    outputFileStream.close();
                }
            }

            tarInputStream.close();
            gzipInputStream.close();
            bufferedInputStream.close();
            fileInputStream.close();
            
            log.info("文件解压完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String sourceFile = "D:\\tar\\6.tar.gz";
        String destinationFolder = "D:\\TestDownload\\jie";

        try {
            extractTarGzFile(sourceFile, destinationFolder);
            System.out.println("Extraction completed successfully.");
        } catch (Exception e) {
            System.out.println("Error occurred during extraction: " + e.getMessage());
        }
    }
}
相关推荐
间彧3 分钟前
Spring Boot项目中,Redis 如何同时执行多条命令
java·redis
召摇27 分钟前
如何避免写垃圾代码:Java篇
java·后端·代码规范
vker29 分钟前
第 1 天:单例模式(Singleton Pattern)—— 创建型模式
java·设计模式
我不是混子35 分钟前
什么是内存泄漏?
java
程序员小假35 分钟前
我们来说说当一个线程两次调用 start() 方法会出现什么情况?
java·后端
SimonKing1 小时前
Archery:开源、一站式的数据库 SQL 审核与运维平台
java·后端·程序员
皮皮林55113 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
卡尔特斯17 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
白鲸开源17 小时前
Ubuntu 22 下 DolphinScheduler 3.x 伪集群部署实录
java·ubuntu·开源
ytadpole17 小时前
Java 25 新特性 更简洁、更高效、更现代
java·后端