public static void deCompressGZipFile(String tarGzFile, String destDir) throws EmergencyFireException{
log.info(tarGzFile + " 开始解压");
// 建立输出流,用于将从压缩文件中读出的文件流写入到磁盘
TarArchiveEntry entry = null;
TarArchiveEntry[] subEntries = null;
File subEntryFile = null;
try (FileInputStream fis = new FileInputStream(tarGzFile);
GZIPInputStream gis = new GZIPInputStream(fis);
TarArchiveInputStream taris = new TarArchiveInputStream(gis);) {
while ((entry = taris.getNextTarEntry()) != null) {
StringBuilder entryFileName = new StringBuilder();
entryFileName.append(destDir).append(File.separator).append(entry.getName());
File entryFile = new File(entryFileName.toString());
if (entry.isDirectory()) {
if (!entryFile.exists()) {
entryFile.mkdir();
}
subEntries = entry.getDirectoryEntries();
for (int i = 0; i < subEntries.length; i++) {
try (OutputStream out = new FileOutputStream(subEntryFile)) {
subEntryFile = new File(entryFileName + File.separator + subEntries[i].getName());
IOUtils.copy(taris, out);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
checkFileExists(entryFile);
OutputStream out = new FileOutputStream(entryFile);
IOUtils.copy(taris, out);
out.close();
// 如果是gz文件进行递归解压
if (entryFile.getName().endsWith(".gz")) {
deCompressGZipFile(entryFile.getPath(), destDir);
}
}
}
log.info(tarGzFile + " 解压完成");
// 如果需要刪除之前解压的gz文件,在这里进行
} catch (Exception e) {
log.error(tarGzFile + " 解压失败", e);
throw new EmergencyFireException(5000, "解压失败");
}
}
java解压tar.gz文件
最新推荐文章于 2023-11-01 15:34:29 发布