java 如何从 GZIPInputstream 读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35789253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:35:29  来源:igfitidea点击:

How to read from GZIPInputstream

java

提问by Aajan

Scenario is to read a gzip file(.gz extension)

场景是读取一个 gzip 文件(.gz 扩展名)

Got to know that there is GZIPInputStream class to handle this.

知道有 GZIPInputStream 类来处理这个。

Here is the code to convert file object to GZIPStream.

这是将文件对象转换为 GZIPStream 的代码。

FileInputStream fin = new FileInputStream(FILENAME);
 GZIPInputStream gzis = new GZIPInputStream(fin);

Doubt is how to read content from this 'gzis' object?

疑问是如何从这个“gzis”对象中读取内容?

回答by Kordi

Decode bytes from an InputStream, you can use an InputStreamReader. A BufferedReader will allow you to read your stream line by line.

从 InputStream 解码字节,您可以使用 InputStreamReader。BufferedReader 将允许您逐行读取流。

If the zip is a TextFile

如果 zip 是 TextFile

ByteArrayInputStream bais = new ByteArrayInputStream(responseBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);

String readed;
while ((readed = in.readLine()) != null) {
  System.out.println(readed);
}

As noticed in the comments. It will ignore the encoding, and perhaps not work always properly.

正如评论中所注意到的。它将忽略编码,并且可能无法始终正常工作。

Better Solution

更好的解决方案

It will write the uncompressed data to the destinationPath

它将未压缩的数据写入destinationPath

FileInputStream fis = new FileInputStream(sourcePath);
FileOutputStream fos = new FileOutputStream(destinationPath);
GZIPInputStream gzis = new GZIPInputStream(fis);
byte[] buffer = new byte[1024];
int len = 0;

while ((len = gzis.read(buffer)) > 0) {
    fos.write(buffer, 0, len);
}

fos.close();
fis.close();
gzis.close();

回答by Evgeny Lebedev

I recommended you to use Apache Commons Compress API

我建议你使用Apache Commons Compress API

add Maven dependency:

添加Maven依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.10</version>
</dependency>

then use GZipCompressorInputStreamclass, example described here

然后使用GZipCompressorInputStream类,此处描述的示例