java 压缩 tar_在java中实现tar,gzip功能

本文介绍了一个用于将多个文件压缩成tar.gz格式的实用工具。该工具能够处理大量的输入文件,并支持超过8GB的大文件压缩,同时兼容长文件名。通过递归方式处理目录,实现了高效的文件压缩。

(1);

list.add(file);

compressFiles(list, output);

}

/**

* Compress (tar.gz) the input files to the output file

*

* @param files The files to compress

* @param output The resulting output file (should end in .tar.gz)

* @throws IOException

*/

public static void compressFiles(Collectionfiles, File output)

throws IOException

{

LOG.debug("Compressing "+files.size() + " to "+output.getAbsoluteFile());

// Create the output stream for the output file

FileOutputStream fos = new FileOutputStream(output);

// Wrap the output file stream in streams that will tar and gzip everything

TarArchiveOutputStream taos = new TarArchiveOutputStream(

new GZIPOutputStream(new BufferedOutputStream(fos)));

// TAR has an 8 gig file limit by default, this gets around that

taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); // to get past the 8 gig limit

// TAR originally didn't support long file names, so enable the support for it

taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

// Get to putting all the files in the compressed output file

for (File f : files) {

addFilesToCompression(taos, f, ".");

}

// Close everything up

taos.close();

fos.close();

}

/**

* Does the work of compression and going recursive for nested directories

*

*

* Borrowed heavily from http://www.thoughtspark.org/node/53

*

* @param taos The archive

* @param file The file to add to the archive

* @param dir The directory that should serve as the parent directory in the archivew

* @throws IOException

*/

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

throws IOException

{

// Create an entry for the file

taos.putArchiveEntry(new TarArchiveEntry(file, dir+FILE_SEPARATOR+file.getName()));

if (file.isFile()) {

// Add the file to the archive

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

IOUtils.copy(bis, taos);

taos.closeArchiveEntry();

bis.close();

}

else if (file.isDirectory()) {

// close the archive entry

taos.closeArchiveEntry();

// go through all the files in the directory and using recursion, add them to the archive

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

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

}

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值