Java 实现*.tar.gz文件压缩和解压

GZIPUtil类提供了gzip文件压缩和解压缩工具方法。包括将一组文件打包成.tar文件,然后压缩为.tar.gz文件,以及解压.tar.gz文件到指定目录。主要使用了Apache Commons Compress和Java内置的压缩流进行操作。

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

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Title: GZIPUtil.java
 * @Description: gzip file compression and decompression tool classes
 * @author zp
 * @date
 * @version V1.0
 */
public class GZIPUtil {
    //in order to gzip file to tar.gz,we need to get *.tar file

    /**
     *
     * @Title: pack
     * @Description: Copy a set of files into tar packages
     * @param sources An array of original files to be packed
     * @param target Define the file after the tar package
     * @return File     return the tar file
     * @throws
     */
    public static File pack(File[] sources, File target){
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(target);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        TarArchiveOutputStream os = new TarArchiveOutputStream(out);
        for (File file : sources) {
            try {
                os.putArchiveEntry(new TarArchiveEntry(file));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(os != null) {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return target;
    }
    //get *.tar.gz file
    /**
     *
     * @Title: compress
     * @Description: Compress the file with gzip
     * @param  source the files needed to be compress
     * @return File   the *.gz file
     * @throws
     */
    public static File compress(File source) {
        File target = new File(source.getName() + ".gz");
        FileInputStream in = null;
        GZIPOutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new GZIPOutputStream(new FileOutputStream(target));
            byte[] array = new byte[1024];
            int number = -1;
            while((number = in.read(array, 0, array.length)) != -1) {
                out.write(array, 0, number);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return target;
    }


    /**
     * Unzip the tar.gz file
     * @param file the object file needed to be unzip
     * @param outputDir
     * @throws IOException
     */
    public static void unTarGz(String file, String outputDir) throws IOException{
        TarInputStream tarIn = null;
        try{
            tarIn = new TarInputStream(new GZIPInputStream(
                    new BufferedInputStream(new FileInputStream(file))),
                    1024 * 2);

            createDirectory(outputDir,null);//创建输出目录

            TarEntry entry = null;
            while( (entry = tarIn.getNextEntry()) != null ){

                if(entry.isDirectory()){//是目录
                    entry.getName();
                    createDirectory(outputDir,entry.getName());//创建空目录
                }else{//是文件
                    File tmpFile = new File(outputDir + "/" + entry.getName());
                    createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
                    OutputStream out = null;
                    try{
                        out = new FileOutputStream(tmpFile);
                        int length = 0;

                        byte[] b = new byte[2048];

                        while((length = tarIn.read(b)) != -1){
                            out.write(b, 0, length);
                        }

                    }catch(IOException ex){
                        throw ex;
                    }finally{

                        if(out!=null)
                            out.close();
                    }
                }
            }
        }catch(IOException ex){
            throw new IOException("解压归档文件出现异常",ex);
        } finally{
            try{
                if(tarIn != null){
                    tarIn.close();
                }
            }catch(IOException ex){
                throw new IOException("关闭tarFile出现异常",ex);
            }
        }
    }



    /**
     * Create a file directory
     * @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 IOException {
        //sources:Gets an array of files that require tar compression
        File[] sources = new File[] {new File("C:\\Users\\Administrator\\Desktop\\sql\\test.sql"),
                new File("C:\\Users\\Administrator\\Desktop\\sql\\weibo2.txt")};
        //Define   a the *.tar file ,the file in sources will be tar to the target
        File target = new File("C:\\Users\\Administrator\\Desktop\\release_package.tar");
        //compress the files into *.tar.gz
        compress(pack(sources, target));

        //Extract the * .tar.gz file,need the *.tar.gz and the outputDir
        unTarGz("D:\\file\\work\\tools\\mengJun\\release_package.tar.gz","C:\\Users\\Administrator\\Desktop\\新建文件夹 (2)");
        /* unGzipFile("C:\\Users\\Administrator\\Desktop\\release_package.tar.gz"); */
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值