首页 > 其他 > 详细

tar.gz文件解压

时间:2019-06-14 19:28:33      阅读:161      评论:0      收藏:0      [点我收藏+]

try(Resource res=XX ()){

  work with res

}

try-with-resource是JDK1.7的新特性,()括号里的内容支持包括流以及任何可关闭的资源,数据流(其他资源)会在try块执行完毕之后自动被关闭,省去了写finally块关闭资源的步骤。

 

//解压tar.gz文件

    /*

    * @param sourceFile要解压的文件

    * @param target 要解压到的目录

    */

    private void untarFile(File sourceFile,String target) throws IOException{

        if(sourceFile.exists() && sourceFile.isFile()){

            try(TarArchiveInputStream tarIn=new TarArchiveInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(sourceFile))))){

                TarArchiveEntry entry=null;

                while((entry=tarIn.getNextTarEntry())!=null) {

                   File tarFile=new File(target,entry.getName());

                   if(entry.isDirectory()) {//是目录,创建目录

                      tarFile.mkdirs();

                   }else {//是文件

                        if(tarFile.getParentFile().exists()) {//可能存在创建目录延迟,父目录还没创建好,找不着
                               tarFile.getParentFile().mkdirs();
        }

                       try(OutputStream out=new FileOutputStream(tarFile)){

                           int length=0;

                           byte[] b=new byte[2048];

                           while((length=tarIn.read())!=-1) {

                               out.write(b,0,length);

                           }

                       }catch (Exception e) {

                           // TODO: handle exception

                       }

                   }

                }

            }catch (Exception e) {

                // TODO: handle exception

            }

        }

    }

 

需要引入的包

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;

tar.gz文件解压

原文:https://www.cnblogs.com/hairtutu/p/11024943.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!