java 压缩 tar.gz_java – 使用Commons Compress将目录压缩到tar.gz

本文探讨了使用commons压缩库创建tar.gz文件时遇到的问题,即压缩后的文件在解压时形成嵌套而非预期的目录结构。作者分享了具体的代码实现,并寻求帮助以解决这一难题。

我正在使用commons压缩库来创建目录的tar.gz.我有一个目录结构如下.

parent/

child/

file1.raw

fileN.raw

我正在使用以下代码进行压缩.它运行良好,没有例外.但是,当我尝试解压缩tar.gz时,我得到一个名为“childDirToCompress”的文件.它的大小正确,因此文件在tarring过程中显然已经相互附加.所需的输出将是一个目录.我无法弄清楚我做错了什么.任何明智的公共审判者都能把我置于正确的道路上吗?

CreateTarGZ() throws CompressorException, FileNotFoundException, ArchiveException, IOException {

File f = new File("parent");

File f2 = new File("parent/childDirToCompress");

File outFile = new File(f2.getAbsolutePath() + ".tar.gz");

if(!outFile.exists()){

outFile.createNewFile();

}

FileOutputStream fos = new FileOutputStream(outFile);

TarArchiveOutputStream taos = new TarArchiveOutputStream(new GZIPOutputStream(new BufferedOutputStream(fos)));

taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);

taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

addFilesToCompression(taos, f2, ".");

taos.close();

}

private static void addFilesToCompression(TarArchiveOutputStream taos, File file, String dir) throws IOException{

taos.putArchiveEntry(new TarArchiveEntry(file, dir));

if (file.isFile()) {

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

IOUtils.copy(bis, taos);

taos.closeArchiveEntry();

bis.close();

}

else if(file.isDirectory()) {

taos.closeArchiveEntry();

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

addFilesToCompression(taos, childFile, file.getName());

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值