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());
        }
    }
}

你可能感兴趣的:(springboot,java,java,开发语言)