java 压缩技术_Java压缩技术 - tar.bz2解压缩

前言

从网络上下载的源码包,最常见的是tar.gz包,还有一部分是tar.bz2包,这篇文章以解压tar.bz2文件为示例来讲解Java的解压操作。

.tar: 打包

.bz2: 由具有高压缩率的压缩工具bzip2压缩

linux中的压缩和解压命令:

压缩:

tar -cjf test.tar.bz2 test

解压:

tar -jxvf test.tar.bz2

准备

由于需要使用TarInputStream类,在pom.xml中增加如下依赖:

org.apache.ant

ant

1.9.7

由于需要使用BZip2CompressorInputStream类,在pom.xml中增加如下依赖:

org.apache.commons

commons-compress

1.18

tar.bz2文件解压

创建目录:

/**

* 构建目录

* @param outputDir 输出目录

* @param subDir 子目录

*/

private static void createDirectory(String outputDir, String subDir){

File file = new File(outputDir);

if(!(subDir == null || subDir.trim().equals(""))) {//子目录不为空

file = new File(outputDir + File.separator + subDir);

}

if(!file.exists()){

if(!file.getParentFile().exists()){

file.getParentFile().mkdirs();

}

file.mkdirs();

}

}

解压缩tar.bz2文件

/**

* 解压缩tar.bz2文件

* @param file 压缩包文件

* @param targetPath 目标文件夹

* @param delete 解压后是否删除原压缩包文件

*/

public static void decompressTarBz2(File file, String targetPath, boolean delete){

FileInputStream fis = null;

OutputStream fos = null;

BZip2CompressorInputStream bis = null;

TarInputStream tis = null;

try {

fis = new FileInputStream(file);

bis = new BZip2CompressorInputStream(fis);

tis = new TarInputStream(bis, 1024 * 2);

// 创建输出目录

createDirectory(targetPath, null);

TarEntry entry;

while((entry = tis.getNextEntry()) != null){

if(entry.isDirectory()){

createDirectory(targetPath, entry.getName()); // 创建子目录

}else{

fos = new FileOutputStream(new File(targetPath + File.separator + entry.getName()));

int count;

byte data[] = new byte[2048];

while ((count = tis.read(data)) != -1) {

fos.write(data, 0, count);

}

fos.flush();

}

}

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

if(fis != null){

fis.close();

}

if(fos != null){

fos.close();

}

if(bis != null){

bis.close();

}

if(tis != null){

tis.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

更多java相关,请查看:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值