700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java 压缩 tar_Java将文本文件压缩为tar.gz

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

时间:2023-02-26 06:04:23

相关推荐

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"));

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。