package org.jeecg.runner;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import java.io.*;

public class TarUtils {
    public static void main(String[] args) throws IOException {
        tarFile("G:/Demo/cfcs_plugin.ini","G:/Demo/测试.tar");
        unTarFile("G:/Demo/测试","G:/Demo/测试.tar");
    }

    /**
     *压缩tar包
     *
     * @param filePath  文件路径
     * @param tarPath   tar包生成路径
     * @throws IOException
     */
    public static void tarFile(String filePath,String tarPath) throws IOException {
        File file = new File(filePath);
        TarArchiveEntry tae = new TarArchiveEntry(file);
        tae.setSize(file.length());
        //不加tae.setName,压缩文件里是全路径(filePath有几层,压缩包里有几层)
        tae.setName(new String(file.getName().getBytes("GBK"),"ISO-8859-1"));
        TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(new File(tarPath)));
        taos.putArchiveEntry(tae);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int count;
        byte data[] = new byte[1024];
        while((count = bis.read(data,0,1024)) !=-1){
            taos.write(data,0,count);
        }
        bis.close();
        taos.closeArchiveEntry();
    }

    /**
     * 解压tar包
     *
     * @param unTarPath     解压缩tar包路径
     * @param tarPath       tar包路径
     * @throws IOException
     */
    public static void unTarFile(String unTarPath,String tarPath) throws IOException {
        TarArchiveEntry tae = null;
        TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(new File(tarPath)));
        while((tae = tais.getNextTarEntry()) != null){
            String dir = unTarPath + File.separator + tae.getName();
            File dirFile = new File(dir);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dirFile));
            int count;
            byte data[] = new byte[1024];
            while((count = tais.read(data,0,1024)) !=-1){
                bos.write(data,0,count);
            }
            bos.close();
        }
    }
}

 

 

posted on 2022-05-30 09:18  月零Ray  阅读(2306)  评论(0编辑  收藏  举报