java文件解压文件_Java文件解压之TGZ解压

package com.alibaba.intl.batch.dependency;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

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

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

import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;

import org.apache.commons.compress.utils.IOUtils;

import org.apache.commons.lang3.StringUtils;

/**

* 解压工具类

* @author hollis

*

*/

public class PackDecompressor {

public static int BUFFER_SIZE = 2048;

public static void main(String[] args) throws Exception {

unTarGZ("/home/hollis/Downloads/a.tgz", "/home/hollis/Downloads/a");

}

public static void unTarGZ(String file,String destDir) throws Exception{

File tarFile = new File(file);

unTarGZ(tarFile, destDir);

}

public static void unTarGZ(File tarFile,String destDir) throws Exception{

if(StringUtils.isBlank(destDir)) {

destDir = tarFile.getParent();

}

destDir = destDir.endsWith(File.separator) ? destDir : destDir + File.separator;

unTar(new GzipCompressorInputStream(new FileInputStream(tarFile)), destDir);

}

private static void unTar(InputStream inputStream, String destDir) throws Exception {

TarArchiveInputStream tarIn = new TarArchiveInputStream(inputStream, BUFFER_SIZE);

TarArchiveEntry entry = null;

try {

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

if (entry.isDirectory()) {//是目录

createDirectory(destDir, entry.getName());//创建空目录

} else {//是文件

File tmpFile = new File(destDir + File.separator + entry.getName());

createDirectory(tmpFile.getParent() + File.separator, 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);

}

} finally {

IOUtils.closeQuietly(out);

}

}

}

} catch (Exception e) {

e.printStackTrace();

throw e;

} finally {

IOUtils.closeQuietly(tarIn);

}

}

public static void createDirectory(String outputDir,String subDir){

File file = new File(outputDir);

if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空

file = new File(outputDir + File.separator + subDir);

}

if(!file.exists()){

file.mkdirs();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值