简体   繁体   English

如何从GZIPInputstream读取

[英]How to read from GZIPInputstream

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'对象的内容?

Decode bytes from an InputStream, you can use an InputStreamReader. 从InputStream解码字节,您可以使用InputStreamReader。 A BufferedReader will allow you to read your stream line by line. 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();

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 GZipCompressorInputStream class, example described here 然后使用GZipCompressorInputStream类, 这里描述的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM