java将文件压缩成tar.gz

本文介绍了一种使用Java实现将多个文件打包并压缩为tar.gz格式的方法。通过创建TarEntry来处理每个文件,并使用TarOutputStream进行打包,接着利用GZIPOutputStream完成gzip压缩。文章提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public static File compressTarFile(List<File> list, String  targzipFilePath, String targzipFileName){    

     byte[] buf = new byte[1024]; //设定读入缓冲区尺寸     

     try{     

         //建立压缩文件输出流     

         FileOutputStream fout=new FileOutputStream(targzipFilePath+"test.tar.gz");    

         //建立tar压缩输出流     

         TarOutputStream tout=new TarOutputStream(fout);    

         for(File file : list){    

             //打开需压缩文件作为文件输入流     

             FileInputStream fin=new FileInputStream(file);   //filename是文件全路径    

             TarEntry tarEn=new TarEntry(file); //此处必须使用new TarEntry(File file);    

             tarEn.setName(file.getName());  //此处需重置名称,默认是带全路径的,否则打包后会带全路径    

             tout.putNextEntry(tarEn);      

             int num = -1;     

             while ((num=fin.read(buf)) > 0){     

                 tout.write(buf,0,num);     

             }     

             tout.closeEntry();    

             fin.close();     

         }    

         tout.close();       

         fout.close();  

         //建立压缩文件输出流  

        FileOutputStream gzFile=new FileOutputStream(targzipFilePath+targzipFileName);   

       //建立gzip压缩输出流  

        GZIPOutputStream gzout=new GZIPOutputStream(gzFile);   

       //打开需压缩文件作为文件输入流  

        FileInputStream tarin=new FileInputStream(targzipFilePath+"test.tar.gz");     

       int len;   

       while((len=tarin.read(buf)) != -1){   

            gzout.write(buf,0,len);   

        }   

        gzout.close();   

        gzFile.close();   

        tarin.close();

         return new File(targzipFilePath+targzipFileName);

     }catch(Exception e){    

       e.printStackTrace();    

     }  

     return null ; 

  }

 

先归档,后压缩

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值