如何从GZIPInputstream读取 [英] How to read from GZIPInputstream

查看:2228
本文介绍了如何从GZIPInputstream读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

要知道有GZIPInputStream类来处理这个问题。

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

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

Here is the code to convert file object to GZIPStream.

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

怀疑是如何阅读这个'gzis'对象的内容?

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

推荐答案

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

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

如果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.

更好的解决方案

它会将未压缩的数据写入destinationPath

It will write the uncompressed data to the 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();

这篇关于如何从GZIPInputstream读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆