java打包tar.gz_通过 Java 压缩文件,打包一个 tar.gz 采集器包

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;

import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

import org.apache.commons.io.IOUtils;

import java.io.*;

import java.util.zip.GZIPOutputStream;

public class TarUtils {

public static void compress(String sourceFolder, String tarGzPath) throws IOException {

createTarFile(sourceFolder, tarGzPath);

}

private static void createTarFile(String sourceFolder, String tarGzPath) {

TarArchiveOutputStream tarOs = null;

try {

// 创建一个 FileOutputStream 到输出文件(.tar.gz)FileOutputStream fos = new FileOutputStream(tarGzPath);

// 创建一个 GZIPOutputStream,用来包装 FileOutputStream 对象GZIPOutputStream gos = new GZIPOutputStream(new BufferedOutputStream(fos));

// 创建一个 TarArchiveOutputStream,用来包装 GZIPOutputStream 对象

tarOs = new TarArchiveOutputStream(gos);

// 若不设置此模式,当文件名超过 100 个字节时会抛出异常,异常大致如下:

// is too long ( > 100 bytes)

// 具体可参考官方文档:http://commons.apache.org/proper/commons-compress/tar.html#Long_File_Names

tarOs.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);

addFilesToTarGZ(sourceFolder, "", tarOs);

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

tarOs.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

public static void addFilesToTarGZ(String filePath, String parent, TarArchiveOutputStream tarArchive) throws IOException {

File file = new File(filePath);

// Create entry name relative to parent file pat

String entryName = parent + file.getName();

// 添加 tar ArchiveEntry

tarArchive.putArchiveEntry(new TarArchiveEntry(file, entryName));

if (file.isFile()) {

FileInputStream fis = new FileInputStream(file);

BufferedInputStream bis = new BufferedInputStream(fis);

// 写入文件

IOUtils.copy(bis, tarArchive);

tarArchive.closeArchiveEntry();

bis.close();

} else if (file.isDirectory()) {

// 因为是个文件夹,无需写入内容,关闭即可

tarArchive.closeArchiveEntry();

// 读取文件夹下所有文件

for (File f : file.listFiles()) {

// 递归

addFilesToTarGZ(f.getAbsolutePath(), entryName + File.separator, tarArchive);

}

}

}

public static void main(String[] args) throws IOException {

// 测试一波,将 filebeat-7.1.0-linux-x86_64 打包成名为 filebeat-7.1.0-linux-x86_64.tar.gz 的 tar 包

compress("/Users/a123123/Work/filebeat-7.1.0-linux-x86_64", "/Users/a123123/Work/tmp_files/filebeat-7.1.0-linux-x86_64.tar.gz");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值