Java之解压Tar.gz和Gz文件到指定的目录下

工作中的需求:需要读取指定路径下的压缩文件,然后解压到指定的目录下

引入maven依赖

<dependency>
     <groupId>org.apache.ant</groupId>
     <artifactId>ant</artifactId>
     <version>1.10.5</version>
</dependency>
package com.example.javacode;

import org.apache.tools.tar.TarInputStream;
import java.io.*;
import java.util.zip.GZIPInputStream;

/**
 * @program: JavaCode
 * @ClassName FileUtils
 * @description:
 * @author: ltcz99
 * @create: 2023-04-16
 * @Version 1.0
 **/
public class FileUtils {


    /**
     * 解压tar.gz文件到指定目录
     * @param sourceDir 源文件夹
     * @param destDir 解压后的目标文件夹
     */
    public static void unTarGz(String sourceDir,String destDir) throws Exception{
        File outFile = new File(sourceDir);
        File[] files = outFile.listFiles();
        try{
            //创建输出目录
            createDirectory(destDir,null);
            TarInputStream tarIn;
            int index = 1;
            for (File file : files){
                if(file.getName().contains("tar.gz")){
                    tarIn = new TarInputStream(new GZIPInputStream(
                            new BufferedInputStream(new FileInputStream(file))),
                            1024 * 2);
                    String outFileName = destDir + "/" +index+++ ".log";
                    OutputStream out = new FileOutputStream(outFileName);
                    int length = 0;
                    byte[] b = new byte[2048];
                    while ((length = tarIn.read(b)) != -1){
                        out.write(b,0,length);
                    }
                    out.close();
                    tarIn.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 解压gz到指定的文件夹下面
     * @param sourceDir
     * @param destDir
     */
    public static void unGzipFile(String sourceDir,String destDir) {
        //创建输出目录
        createDirectory(destDir,null);
        File sourceFile = new File(sourceDir);
        File[] files = sourceFile.listFiles();
        try {
            int index = 1;
            for(File file : files){
                if(file.getName().contains("gz")){
                    FileInputStream fin = new FileInputStream(file);
                    //建立gzip解压工作流
                    GZIPInputStream gzin = new GZIPInputStream(fin);
                    //建立解压文件输出流
                    File tmpFile = new File(destDir + "/" + index++  +".log");
                    FileOutputStream fout = new FileOutputStream(tmpFile);
                    int length;
                    byte[] buf = new byte[2048];
                    while ((length = gzin.read(buf, 0, buf.length)) != -1) {
                        fout.write(buf, 0, length);
                    }
                    gzin.close();
                    fout.close();
                    fin.close();
                }
            }
        } catch (Exception ex) {
            System.err.println(ex);
        }
    }

    /**
     * 读取文件到指定的文件夹下面
     * @param sourceLogPath
     * @param destLogPath
     */
    public static void readFileToDestLogPath(String sourceLogPath, String destLogPath) {
        File sourceFile = new File(sourceLogPath);
        File[] files = sourceFile.listFiles();
        for (File file : files){
            String fileName = destLogPath + "/" + file.getName();
            File destFile = new File(fileName);
            if(file.getName().contains("log") && !fileName.contains("gz")){
                try {
                    if(destFile.exists()){
                        destFile.delete();
                    }
                    String logFile = sourceFile + "/" + file.getName();
                    FileInputStream fis = new FileInputStream(logFile);
                    FileOutputStream fos = new FileOutputStream(destFile);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    int len = 0;
                    while ((len = bis.read()) != -1) {
                        bos.write(len);
                    }
                    bos.flush();
                    // 关闭资源
                    fis.close();
                    bis.close();
                    fos.close();
                    bos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

    }
    /**
     * 创建目录
     * @param outputDir
     * @param subDir
     */
    public static void createDirectory(String outputDir,String subDir){
        File file = new File(outputDir);
        //子目录不为空
        if(!(subDir == null || subDir.trim().equals(""))){
            file = new File(outputDir + "/" + subDir);
        }
        if(!file.exists()){
            if(!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.mkdirs();
        }
    }

    public static void main(String[] args) throws Exception {
        String sourceDir = "/Users/ltcz99/Downloads/templog";
        String destDir = "/Users/ltcz99/Downloads/unzip/";
        //解压.gz文件到指定的文件件下面
        unGzipFile(sourceDir,destDir);
        // 解压tar.gz文件到指定的文件夹下面
        unTarGz(sourceDir,destDir);
        //读取特定的文件到指定的文件夹下面
        readFileToDestLogPath(sourceDir,destDir);
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用Apache Commons Compress来解压tar.gz文件。以下是一个示例代码: ```java import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import java.io.*; public class TarGzipExample { public static void main(String[] args) throws IOException { File file = new File("example.tar.gz"); try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); GzipCompressorInputStream gzis = new GzipCompressorInputStream(bis); TarArchiveInputStream tais = new TarArchiveInputStream(gzis)) { TarArchiveEntry entry; while ((entry = tais.getNextTarEntry()) != null) { String name = entry.getName(); File outputFile = new File(name); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (OutputStream out = new FileOutputStream(outputFile); BufferedOutputStream bos = new BufferedOutputStream(out)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = tais.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } } } } } } } ``` 在读取tar.gz文件时,文件路径可能会乱码。这是因为tar格式不支持Unicode字符集,因此在保存文件名时会使用一种转换方法。如果文件名中包含非ASCII字符,那么这种转换方法可能会导致文件名乱码。要解决这个问题,可以使用`org.apache.commons.compress.archivers.tar.TarUtils.parseName()`方法来解析文件名。以下是修改后的代码: ```java import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarUtils; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import java.io.*; public class TarGzipExample { public static void main(String[] args) throws IOException { File file = new File("example.tar.gz"); try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); GzipCompressorInputStream gzis = new GzipCompressorInputStream(bis); TarArchiveInputStream tais = new TarArchiveInputStream(gzis)) { TarArchiveEntry entry; while ((entry = tais.getNextTarEntry()) != null) { String name = TarUtils.parseName(entry.getName(), entry.getHeader().nameBytes).toString(); File outputFile = new File(name); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (OutputStream out = new FileOutputStream(outputFile); BufferedOutputStream bos = new BufferedOutputStream(out)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = tais.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } } } } } } } ``` 这个示例代码会在解压文件时解析文件名,并在保存文件时使用解析后的文件名。这样可以避免文件名乱码问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值