1.先将文件解压为.tar文件
private static void unCompressArchiveGz(String archive) throws IOException {
File file = new File(archive);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
GzipCompressorInputStream gcis = null;
String finalName = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
finalName = file.getParent() + File.separator + fileName;
bos = new BufferedOutputStream(new FileOutputStream(finalName));
try {
gcis = new GzipCompressorInputStream(bis);
byte[] buffer = new byte[1024];
int read = -1;
while ((read = gcis.read(buffer)) != -1) {
bos.write(buffer, 0, read);
}
} catch (Exception e) {
throw e;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
bos.close();
}
if (gcis != null) {
gcis.close();
}
if (bis != null) {
bis.close();
}
}
unCompressTar(finalName);
}
2.解压.tar文件,返回解压后的文件路径
private static String unCompressTar(String finalName) {
File file = new File(finalName);
String basePath = file.getParent() + File.separator;
TarArchiveInputStream tais = null;
FileOutputStream os = null;
TarArchiveEntry entry = null;
String finPath = null;
try {
tais = new TarArchiveInputStream(new FileInputStream(file));
while ((entry = tais.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
new File(basePath + entry.getName()).mkdirs();
} else {
finPath = basePath + entry.getName();
File f = new File(finPath);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if (!f.exists()) {
f.createNewFile();
}
os = new FileOutputStream(f);
byte[] bs = new byte[2048];
int len = -1;
while ((len = tais.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (tais != null) {
tais.close();
}
file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
return finPath;
}