tar.gz文件可以看做先用tar打包,再使用gz进行压缩。
使用org.apache.tools.tar.TarEntry; org.apache.tools.tar.TarInputStream 和 org.apache.tools.tar.TarOutputStream
1 //------------------------------------------------------------------------------------------------------ 2 /** 3 * 解压tar.gz 文件 4 * @param file 要解压的tar.gz文件对象 5 * @param outputDir 要解压到某个指定的目录下 6 * @throws IOException 7 */ 8 public static void unTarGz(File file,String outputDir) throws IOException{ 9 TarInputStream tarIn = null; 10 try{ 11 tarIn = new TarInputStream(new GZIPInputStream( 12 new BufferedInputStream(new FileInputStream(file))), 13 1024 * 2); 14 15 createDirectory(outputDir,null);//创建输出目录 16 17 TarEntry entry = null; 18 while( (entry = tarIn.getNextEntry()) != null ){ 19 20 if(entry.isDirectory()){//是目录 21 entry.getName(); 22 createDirectory(outputDir,entry.getName());//创建空目录 23 }else{//是文件 24 File tmpFile = new File(outputDir + "/" + entry.getName()); 25 createDirectory(tmpFile.getParent() + "/",null);//创建输出目录 26 OutputStream out = null; 27 try{ 28 out = new FileOutputStream(tmpFile); 29 int length = 0; 30 31 byte[] b = new byte[2048]; 32 33 while((length = tarIn.read(b)) != -1){ 34 out.write(b, 0, length); 35 } 36 37 }catch(IOException ex){ 38 throw ex; 39 }finally{ 40 41 if(out!=null) 42 out.close(); 43 } 44 } 45 } 46 }catch(IOException ex){ 47 throw new IOException("解压归档文件出现异常",ex); 48 } finally{ 49 try{ 50 if(tarIn != null){ 51 tarIn.close(); 52 } 53 }catch(IOException ex){ 54 throw new IOException("关闭tarFile出现异常",ex); 55 } 56 } 57 }
使用到的包头有:
1 import java.io.BufferedInputStream; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 9 import java.nio.charset.Charset; 10 import java.util.Enumeration; 11 import java.util.zip.GZIPInputStream; 12 import java.util.zip.ZipEntry; 13 import java.util.zip.ZipFile; 14 15 import org.apache.tools.tar.TarEntry; 16 import org.apache.tools.tar.TarInputStream; 17 import org.apache.tools.tar.TarOutputStream;