[英]How to read from GZIPInputstream
场景是读取gzip文件(.gz扩展名)
要知道有GZIPInputStream类来处理这个问题。
这是将文件对象转换为GZIPStream的代码。
FileInputStream fin = new FileInputStream(FILENAME);
GZIPInputStream gzis = new GZIPInputStream(fin);
怀疑是如何阅读这个'gzis'对象的内容?
从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);
}
正如评论中所注意到的那样 它将忽略编码,并且可能无法正常工作。
改善方案
它会将未压缩的数据写入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();
我建议你使用Apache Commons Compress API
添加Maven依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.10</version>
</dependency>
然后使用GZipCompressorInputStream
类, 这里描述的例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.