【问题标题】:How to read from GZIPInputstream如何从 GZIPInputstream 中读取
【发布时间】:2016-06-17 18:53:18
【问题描述】:

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

知道有 GZIPInputStream 类来处理这个。

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

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

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

【问题讨论】:

  • 我很困惑,那只是一个 InputStream,你读它就像读其他 InputStream 一样。
  • 不过,您可能会混淆 zip 和 gzip。
  • 是的,它的 gzip 不是 zip。我更新了。
  • 您读取 GZIPInputStream 的方式与读取 FileInputStream 的方式完全相同(如果数据没有经过 GZipped)。如果是二进制,则读入字节数组。如果是文本,则使用 InputStreamReader 进行包装,指定字符编码。

标签: java


【解决方案1】:

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

如果 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);
}

正如在 cmets 中注意到的那样。它将忽略编码,并且可能无法始终正常工作。

更好的解决方案

它将未压缩的数据写入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();

【讨论】:

  • 假设压缩后的内容是文本,而不是二进制数据。
  • 这假定内容是文本,并且由行组成。并忽略可能使用的编码
  • 内容仅为文字。你说的ingores编码是什么意思?
  • 如果内容仅为文本,则使用第一个解决方案。然后它只输出字符串。第二种解决方案将解压缩的文件写入目标路径。
  • @Andreas 现在满意了。感谢您的通知。
【解决方案2】:

我推荐你使用Apache Commons Compress API

添加 Maven 依赖:

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

然后使用GZipCompressorInputStream类,示例描述here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多