使用GZIPInputStream解壓gz文件
摘要:Spring Boot項目使用GZIPInputStream解壓gz文件,并寫入指定目錄。
問題背景
??一位【菜雞】測試開發工程師說無法解析線上環境的一些壓縮文件,強烈要求幫忙解析一下。
實現方案
??這里提供一個基于Spring Boot項目使用 GZIPInputStream 解壓gz文件的示例,解決了小白的問題。示例文件放置在src/main/resources/static/樓蘭胡楊log.gz,我們解壓后放置到/Users/xxx/yyy/output.txt。
方案的基本步驟:
- 選擇必要的庫:使用 java.util.zip.GZIPInputStream 和其他 IO 類,不必導入庫。
- 創建輸入流:使用Thread.currentThread().getContextClassLoader().getResourceAsStream打開 .gz 文件作為輸入流。
- 解壓文件:使用 GZIPInputStream 讀取壓縮輸入流并解壓。
- 寫入輸出文件:將解壓后的數據流寫到一個新的文件中,完成解壓。
??實現代碼如下:
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文件,希望對你有所幫助。
讀后有收獲,小禮物走一走,請作者喝咖啡。
Buy me a coffee. ?Get red packets.作者:樓蘭胡楊
本文版權歸作者和博客園共有,歡迎轉載,但請注明原文鏈接,并保留此段聲明,否則保留追究法律責任的權利。

浙公網安備 33010602011771號