场景是读取gzip文件(.gz扩展名)
要知道有一个GZIPInputStream类来处理这个问题。
下面是将文件对象转换为GZIPStream的代码。
FileInputStream fin = new FileInputStream(FILENAME);
GZIPInputStream gzis = new GZIPInputStream(fin);疑惑是如何从这个'gzis‘对象中读取内容?
发布于 2016-03-04 14:23:59
从InputStream中解码字节,您可以使用InputStreamReader。BufferedReader将允许您逐行读取您的流。
如果压缩文件是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();发布于 2016-03-04 18:21:21
我推荐你使用Apache Commons Compress API
添加Maven依赖项:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.10</version>
</dependency>然后使用GZipCompressorInputStream类,以here为例描述
https://stackoverflow.com/questions/35789253
复制相似问题