Java语言TAR文件(文件夹)批量打包&压缩

最近项目中需要将文件和文件夹一起打包压缩为tar.gz文件,特此记录便于日后查阅。 

package com.openailab.oascloud.file.util;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @author zhangzhixiang
 * @version V1.0
 * @Title: GZIPUtil.java
 * @Description: 文件压缩工具类
 * @date 2020-01-07 19:40:50
 */
public class GZIPUtil {

    private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class);

    /**
     * tar文件批量打包(仅限于文件打包)
     *
     * @param sources
     * @param target
     * @return java.io.File
     * @author zxzhang
     * @date 2020/1/7
     */
    public static File pack(File target, File[] sources) {
        try (FileOutputStream out = new FileOutputStream(target); TarArchiveOutputStream os = new TarArchiveOutputStream(out)) {
            for (File file : sources) {
                os.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return target;
    }

    /**
     * tar文件批量打包(支持文件&文件夹打包)
     *
     * @param destFilePath
     * @param files
     * @return java.lang.String
     * @author zxzhang
     * @date 2020/3/10
     */
    public static String tarFiles(String destFilePath, File... files) throws IOException {
        File destFile = new File(destFilePath);
        if (destFile.exists()) {
            LOG.error("********目标文件已存在,destFilePath:{}********" + destFilePath);
            return "目标文件已存在,destFilePath:" + destFilePath;
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(destFile);
             BufferedOutputStream bufferedWriter = new BufferedOutputStream(fileOutputStream);
             TarArchiveOutputStream tar = new TarArchiveOutputStream(bufferedWriter)) {

            tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

            for (File file : files) {
                addTarArchiveEntryToTarArchiveOutputStream(file, tar, "");
            }
        }
        return null;
    }

    /**
     * 添加文件到tar输出流中
     *
     * @param file
     * @param tar
     * @param prefix
     * @return void
     * @author zxzhang
     * @date 2020/3/10
     */
    private static void addTarArchiveEntryToTarArchiveOutputStream(File file, TarArchiveOutputStream tar, String prefix) throws IOException {
        TarArchiveEntry entry = new TarArchiveEntry(file, prefix + File.separator + file.getName());

        if (file.isFile()) {
            entry.setSize(file.length());
            tar.putArchiveEntry(entry);
            try (FileInputStream fileInputStream = new FileInputStream(file);
                 BufferedInputStream input = new BufferedInputStream(fileInputStream);) {
                IOUtils.copy(input, tar);
            }
            tar.closeArchiveEntry();
        } else {
            tar.putArchiveEntry(entry);
            tar.closeArchiveEntry();
            prefix += File.separator + file.getName();
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    addTarArchiveEntryToTarArchiveOutputStream(f, tar, prefix);
                }
            }
        }
    }

    /**
     * tar文件压缩
     *
     * @param source
     * @return java.io.File
     * @author zxzhang
     * @date 2020/1/7
     */
    public static File compress(String outDir, File source) {
        File target = new File(outDir + File.separator + 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;
    }

//    public static void main(String[] args) throws IOException {
////        File[] sources = new File[]{new File("/usr/local/oas/zhangzhixiang.txt"), new File("/usr/local/oas/dockerFile")};
////        File target = new File("/usr/local/oas/release_package.tar");
////        pack(sources, target);
////        compress(target);
//        String filePath = "/usr/local/oas";
//        String destFilePath = filePath + File.separator + "zhouhong" + ".tar";
//        tarFiles(destFilePath,
//                new File("/usr/local/oas/dockerFile/"),
//                new File("/usr/local/oas/笔记本文件/"),
//                new File("/usr/local/oas/UUID.info"));
//        compress("/usr/local/oas",new File(destFilePath));
//    }
}

到此 Java语言TAR文件(文件夹)批量打包&压缩介绍完成。

你可能感兴趣的:(Java压缩操作相关)