java 压缩 tar_Java将文本文件压缩为tar.gz

/*** @功能描述 压缩tar.gz 文件

*@paramresourceList 源文件集合

*@paramoutPath 目标文件

*@return返回压缩结果

*@throwsException*/@PrintRunTime(function="压缩tar.gz文件")public static void packet(List resourceList, String outPath) throwsException {//1. 参数验证, 初始化输出路径

if(resourceList == null || resourceList.size() < 1 || !Verify.isEmpty(outPath)){throw new ServiceException("文件压缩执行异常, 非法参数!");

}long startTime =System.currentTimeMillis();//2. 迭代源文件集合, 将文件打包为Tar

try (FileOutputStream fileOutputStream = new FileOutputStream(outPath+".tmp");

BufferedOutputStream bufferedOutput= newBufferedOutputStream(fileOutputStream);

TarOutputStream tarOutputStream= newTarOutputStream(bufferedOutput);) {for(File resourceFile : resourceList) {if(!resourceFile.isFile()){continue;

}try(FileInputStream fileInputStream = newFileInputStream(resourceFile);

BufferedInputStream bufferedInput= newBufferedInputStream(fileInputStream);){

TarEntry entry= new TarEntry(newFile(resourceFile.getName()));

entry.setSize(resourceFile.length());

tarOutputStream.putNextEntry(entry);

IOUtils.copy(bufferedInput, tarOutputStream);

}catch(Exception e) {throw new ServiceException("文件["+resourceFile+"]压缩执行异常, 嵌套异常: \n" +e.toString());

}finally{

tarOutputStream.closeEntry();

}

}

}catch(Exception e) {

Files.delete(Paths.get(outPath+".tmp"));throw new ServiceException("文件压缩至["+outPath+"]执行异常, 嵌套异常: \n" +e.toString());

}//3. 读取打包好的Tar临时文件文件, 使用GZIP方式压缩

try (FileInputStream fileInputStream = new FileInputStream(outPath+".tmp");

BufferedInputStream bufferedInput= newBufferedInputStream(fileInputStream);

FileOutputStream fileOutputStream= newFileOutputStream(outPath);

GZIPOutputStream gzipOutputStream= newGZIPOutputStream(fileOutputStream);

BufferedOutputStream bufferedOutput= newBufferedOutputStream(gzipOutputStream);

) {byte[] cache = new byte[1024];for (int index = bufferedInput.read(cache); index != -1; index =bufferedInput.read(cache)) {

bufferedOutput.write(cache,0,index);

}long endTime =System.currentTimeMillis();

Log.info("文件["+outPath+"]压缩执行完毕, 耗时:" + (endTime - startTime) + "ms");

}catch(Exception e) {throw new ServiceException("文件压缩至["+outPath+"]执行异常, 嵌套异常: \n" +e.toString());

}finally{

Files.delete(Paths.get(outPath+".tmp"));

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值