In this post under Java, I will show with example how to uncompress a gzip format file.
For decompressing a gzip file, we will use java provided “GZIPInputStream” class.
Below is the main code for your reference
Main class
1 package zip;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.util.zip.GZIPInputStream;
8
9 public class Example2 {
10 public static void main(String[] args) throws IOException {
11 File outputFile = new File("OutputFile.pdf");
12 File inputFile = new File("Cir 613-22.pdf.gzip");
13 try(FileInputStream fis = new FileInputStream(inputFile);
14 GZIPInputStream gis = new GZIPInputStream(fis);
15 FileOutputStream fos = new FileOutputStream(outputFile)) {
16 byte[] buffer = new byte[1024];
17 int bytesRead = gis.read(buffer, 0, buffer.length);
18 while(bytesRead != -1) {
19 fos.write(buffer, 0, bytesRead);
20 bytesRead = gis.read(buffer, 0, buffer.length);
21 }
22 fos.flush();
23 }
24 }
25 }
In the above code, at line 11 and 12 I created an input file “Cir 613-22.pdf.gzip” and output file “OutputFile.pdf”.
In the try catch block, I create an input stream “gis” and file output stream “fos”.
The input stream “gis” is wrapper around another input stream “fis” created out of input file.
Then created a buffer of length 1024 bytes. This will store bytes read from input stream “gis”.
Then using “read” method of “gis” we read 1024 bytes of data from input stream and store it in the buffer.
The “read” method returns number of bytes read and this number is stored in variable “bytesRead”.
Next in a loop, we write the bytes read to file output stream “fos”.
Then re-read new bytes from input stream and store the bytes read in the “bytesRead” variable.
This loop will continue until “bytesRead” is -1.
Once we exit the loop, we flush the remaining bytes in the file output stream and close the stream.
In this way we decompress a gzip format file.