java读取tar.gz中指定文件需用apache commons compress库,先用gzipcompressorinputstream解压,再用tararchiveinputstream遍历匹配目标路径并读取内容。

Java 中读取 tar.gz 压缩包里的指定文件,不能直接用 JDK 自带的 java.util.zip(它只支持 ZIP/GZIP,不支持 TAR 格式),需要借助第三方库,最常用的是 Apache Commons Compress。
添加依赖(Maven)
确保项目中引入了 commons-compress 和 commons-io(用于流操作):
<dependency><groupid>org.apache.commons</groupid><artifactid>commons-compress</artifactid><version>1.24.0</version></dependency><dependency><groupid>commons-io</groupid><artifactid>commons-io</artifactid><version>2.15.1</version></dependency>
核心步骤:GZIP → TAR → 定位文件
tar.gz 是先 TAR 打包、再 GZIP 压缩的复合格式,所以要分两层解包:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 用
GzipCompressorInputStream解压 GZIP 流,得到原始 TAR 流 - 用
TarArchiveInputStream遍历 TAR 条目(TarArchiveEntry),匹配目标文件路径 - 找到后,用
read()或IOUtils.toByteArray()读取内容
读取指定文件内容的示例代码
以下方法从 archive.tar.gz 中读取 config.properties 的字节数组(可转为 String 或写入文件):
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.io.IOUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
public static byte[] readTarGzFile(String tarGzPath, String targetFileName) throws IOException {
try (InputStream fis = new FileInputStream(tarGzPath);
InputStream gis = new GzipCompressorInputStream(fis);
TarArchiveInputStream tis = new TarArchiveInputStream(gis)) {
TarArchiveEntry entry;
while ((entry = tis.getNextTarEntry()) != null) {
if (entry.isFile() && entry.getName().equals(targetFileName)) {
return IOUtils.toByteArray(tis); // 读取当前 entry 的全部内容
}
}
throw new FileNotFoundException("File not found in tar.gz: " + targetFileName);
}
}
调用示例:
byte[] content = readTarGzFile("data.tar.gz", "logs/app.log");
String text = new String(content, StandardCharsets.UTF_8);
注意事项
-
路径匹配要精确:TAR 中的文件名包含完整路径(如
app/config.properties),需传入完整路径匹配 - 避免资源泄漏:务必用 try-with-resources 确保所有流正确关闭
- 不支持随机访问:TAR 是顺序结构,无法像 ZIP 那样通过名称直接定位,必须遍历
-
大文件慎用
toByteArray:若目标文件很大,建议用流式处理(如边读边写到 FileOutputStream)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










