Aajan
Aajan

Reputation: 937

How to read from GZIPInputstream

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

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

Here is the code to convert file object to GZIPStream.

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

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

Upvotes: 19

Views: 31400

Answers (2)

Eugene Lebedev
Eugene Lebedev

Reputation: 1474

I recommended you to use Apache Commons Compress API

add Maven dependency:

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

then use GZipCompressorInputStream class, example described here

Upvotes: 2

Kordi
Kordi

Reputation: 2465

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

If the zip is a 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.

Better Solution

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();

Upvotes: 23

Related Questions