最近工作中遇到需要解压tgz文件的问题, 找到commons-compress.jar的工具,用起来感觉很不错。官方的例子:http://commons.apache.org/compress/examples.html
解压tgz或者tar.gz文件分成两步:首先先解压成tar文件,然后解压tar文件。我写了一段简单的示例:
package com.taobao;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
public class Test {
int buffersize = 2048;
public static void main(String[] args) {
String file = "H:\\test.tgz";
Test o = new Test();
File f = o.deCompressTGZFile(file);
o.deCompressTARFile(f);
}
public File deCompressTGZFile(String file) {
return deCompressGZFile(new File(file));
}
private File deCompressGZFile(File file) {
FileOutputStream out = null;
GzipCompressorInputStream gzIn = null;
try {
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
File outFile = new File(file.getParent() + File.separator
+ "tmp.tar");
out = new FileOutputStream(outFile);
gzIn = new GzipCompressorInputStream(in);
final byte[] buffer = new byte[buffersize];
int n = 0;
while (-1 != (n = gzIn.read(buffer))) {
out.write(buffer, 0, n);
}
return outFile;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
out.close();
gzIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void deCompressTARFile(File file) {
String basePath = file.getParent() + File.separator;
TarArchiveInputStream is = null;
try {
is = new TarArchiveInputStream(new FileInputStream(file));
while (true) {
TarArchiveEntry entry = is.getNextTarEntry();
if (entry == null) {
break;
}
if (entry.isDirectory()) {// 这里貌似不会运行到,跟ZipEntry有点不一样
new File(basePath + entry.getName()).mkdirs();
} else {
FileOutputStream os = null;
try {
File f = new File(basePath + entry.getName());
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if (!f.exists()) {
f.createNewFile();
}
os = new FileOutputStream(f);
byte[] bs = new byte[buffersize];
int len = -1;
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
os.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这段代码仅仅为了使用下common-compress.jar包...:)