使用GZIPInputStream解压gz文件

摘要:Spring Boot项目使用GZIPInputStream解压gz文件,并写入指定目录。

问题背景

  一位【菜鸡】测试开发工程师说无法解析线上环境的一些压缩文件,强烈要求帮忙解析一下。

实现方案

  这里提供一个基于Spring Boot项目使用 GZIPInputStream 解压gz文件的示例,解决了小白的问题。示例文件放置在src/main/resources/static/楼兰胡杨log.gz,我们解压后放置到/Users/xxx/yyy/output.txt。

方案的基本步骤

  1. 选择必要的库:使用 java.util.zip.GZIPInputStream 和其他 IO 类,不必导入库。
  2. 创建输入流:使用Thread.currentThread().getContextClassLoader().getResourceAsStream打开 .gz 文件作为输入流。
  3. 解压文件:使用 GZIPInputStream 读取压缩输入流并解压。
  4. 写入输出文件:将解压后的数据流写到一个新的文件中,完成解压。

  实现代码如下:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

/**
 * @Author 楼兰胡杨
 * @Date 2025-07-03
 * @Description: 解压gz文件
 */
public class UnGZIPExample {

    public static void main(String[] args) {
        byte[] buffer = new byte[1024];
        GZIPInputStream gzipStream = null;
        try {
            // 支持相对路径
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/楼兰胡杨log.gz");
            gzipStream = new GZIPInputStream(inputStream);
            // 预期写入文件的绝对路径
            FileOutputStream fos = new FileOutputStream("/Users/xxx/yyy/output.txt");
            int totalLen = 0;
            int length;
            while ((length = gzipStream.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
                totalLen = totalLen + length;
            }
            fos.close();
            System.out.println("解压后文件大小是【" + totalLen + "】bytes");
        } catch (IOException e) {
            System.out.println("解压文件失败");
        } finally {
            if (null != gzipStream) {
                try {
                    gzipStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

  getResourceAsStream的入参中的路径写法是“相对路径”,不带开头的【/】,例如:
✅ "static/楼兰胡杨log.gz"
❌ "/static/楼兰胡杨log.gz" --》这样书写可能找不到文件

结束语

  本文演示了如何使用类加载器的getResourceAsStream(),直接获取文件流,并解压gz文件为txt文件,希望对你有所帮助。

posted @ 2025-07-04 13:44  楼兰胡杨  阅读(41)  评论(0)    收藏  举报