首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从GZIPInputstream中读取

如何从GZIPInputstream中读取
EN

Stack Overflow用户
提问于 2016-03-04 14:17:48
回答 2查看 19.3K关注 0票数 15

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

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

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

代码语言:javascript
复制
FileInputStream fin = new FileInputStream(FILENAME);
 GZIPInputStream gzis = new GZIPInputStream(fin);

疑惑是如何从这个'gzis‘对象中读取内容?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-04 14:23:59

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

如果压缩文件是TextFile,则返回

代码语言:javascript
复制
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);
}

正如评论中所指出的。它将忽略编码,并且可能并不总是正确地工作。

更好的解决方案

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

代码语言:javascript
复制
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();
票数 19
EN

Stack Overflow用户

发布于 2016-03-04 18:21:21

我推荐你使用Apache Commons Compress API

添加Maven依赖项:

代码语言:javascript
复制
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.10</version>
</dependency>

然后使用GZipCompressorInputStream类,以here为例描述

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35789253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档