2013年1月14日 星期一

Decompress (extract) .tgz file in Java

To handle .tgz file, here is a method to handle it in java like handle Zip file.
Use GZIPInputStream to read .tgz file.
Use TarInputStream to read the the GZIPInputStream.
Therefore we can get TarEntry and handle the .tgz file.

Here is an example that we would like to get file named version in a .tgz file.
package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;

public class GZipTest {

 public static void main(String[] args) {
  byte[] buffer = new byte[1024];
  String fileSorce = "/Users/Desktop/testgzip.tgz";

  try {
   // get the zip file content
   TarInputStream zis = new TarInputStream(new GZIPInputStream(
     new FileInputStream(new File(fileSorce))));
   // get the zipped file list entry
   TarEntry ze = zis.getNextEntry();

   while (ze != null) {
    String fileName = ze.getName();
    if (fileName.contains("version")) {
     StringBuffer strBuffer = new StringBuffer();
     while (zis.read(buffer) > 0) {
      strBuffer.append(new String(buffer));
     }
     System.out.println(strBuffer.toString());
    }
    ze = zis.getNextEntry();
   }

   zis.close();
  } catch (IOException e) {
   System.out.println(e);
  }
 }
}