java 7z压缩_springboot Java 7z 高效率压缩文件(org.apache.commons.compress.archivers.sevenz)...

public classCompressUtil {//测试

public static voidmain(String[] args) {

String path= "D:\\Test\\pdf\\2020-01-08\\92b4809959d5478ba5ad5dc676444c06.pdf";//path = "D:\\Test\\pdf\\2020-01-08\\12.txt";

String path2 = "D:\\Test\\pdf\\2020-01-08\\92b4809959d5478ba5ad5dc676444c06z.7z";try{

Compress7z(path,path2);

}catch(Exception e) {

e.printStackTrace();

System.out.println(e.getMessage());

}

}/*** 7z文件压缩

*

*@paraminputFile 待压缩文件夹/文件名

*@paramoutputFile 生成的压缩包名字*/

public static void Compress7z(String inputFile, String outputFile) throwsException {

File input= newFile(inputFile);if (!input.exists()) {throw new Exception(input.getPath() + "待压缩文件不存在");

}

SevenZOutputFile out= new SevenZOutputFile(newFile(outputFile));

compress(out, input,null);

out.close();

}/***@paramname 压缩文件名,可以写为null保持默认*/

//递归压缩

public static void compress(SevenZOutputFile out, File input, String name) throwsIOException {if (name == null) {

name=input.getName();

}

SevenZArchiveEntry entry= null;//如果路径为目录(文件夹)

if(input.isDirectory()) {//取出文件夹中的文件(或子文件夹)

File[] flist =input.listFiles();if (flist.length == 0)//如果文件夹为空,则只需在目的地.7z文件中写入一个目录进入

{

entry= out.createArchiveEntry(input,name + "/");

out.putArchiveEntry(entry);

}else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩

{for (int i = 0; i < flist.length; i++) {

compress(out, flist[i], name+ "/" +flist[i].getName());

}

}

}else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入7z文件中

{

FileInputStream fos= newFileInputStream(input);

BufferedInputStream bis= newBufferedInputStream(fos);

entry=out.createArchiveEntry(input, name);

out.putArchiveEntry(entry);int len = -1;//将源文件写入到7z文件中

byte[] buf = new byte[1024];while ((len = bis.read(buf)) != -1) {

out.write(buf,0, len);

}

bis.close();

fos.close();

out.closeArchiveEntry();

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值