import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.zip.GZIPInputStream;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;
/**
* @Description GZip解压测试
*/
public class GZipTest {
static final int BUFFER = 2048;
public static void main(String argv[]) throws IOException, URISyntaxException {
File file = new File(Thread.currentThread().getContextClassLoader().getResource("curl-7.23.1.tar.gz").toURI());
unZipFile(file, null);
}
public static void unZipFile(File file, String outputDir) {
if(outputDir == null){
outputDir = file.getParent();
}
try {
//建立grip压缩文件输入流
TarInputStream tarIn = new TarInputStream(new GZIPInputStream(new FileInputStream(file)));
TarEntry entry = null;
while( (entry = tarIn.getNextEntry()) != null ){
if(entry.isDirectory()){//是目录
createDirectory(outputDir,entry.getName());//创建空目录
}else{//是文件
File tmpFile = new File(outputDir + "/" + entry.getName());
createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
OutputStream out = null;
try{
out = new FileOutputStream(tmpFile);
int length = 0;
byte[] b = new byte[2048];
while((length = tarIn.read(b)) != -1){
out.write(b, 0, length);
}
}catch(IOException ex){
throw ex;
}finally{
if(out!=null)
out.close();
}
}
}
} catch (Exception ex){
System.err.println(ex.toString());
}
}
/**
* 构建目录
* @param outputDir
* @param subDir
*/
public static void createDirectory(String outputDir,String subDir){
File file = new File(outputDir);
if(subDir != null && !subDir.trim().isEmpty()){//子目录不为空
file = new File(outputDir + "/" + subDir);
}
if(!file.exists()){
file.mkdirs();
}
}
}