java的tgz解压工具类

java的tgz解压工具类前言之前在代码上一直使用的是对 zip 的解压 最近对接方居然使用了 tgz 的压缩包 在网上找了一个工具类 在项目测试 使用 直接贴上 tgz 解压代码 publicclassP publicstatic SIZE 2048 publicstatic String args throws

前言
之前在代码上一直使用的是对zip的解压,最近对接方居然使用了tgz的压缩包,在网上找了一个工具类,在项目测试,使用。
直接贴上tgz解压代码。




public class PackDecompressor { public static int BUFFER_SIZE = 2048; public static void main(String[] args) throws Exception { unTarGZ("D:\\test\\payresult_fix_.txt.tgz", "D:\\test\\aaa"); } 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(); } } } 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/218091.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 上午8:04
下一篇 2026年3月18日 上午8:04


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号