Compressing a file in gzip format

In this post under Java, I will show with example how to compress a single file in gzip format.

For compressing a file in gzip format, we will use java provided “GZIPOutputStream” class.

Below is the main code for your reference

Main Class

1  package zip;
3  import;
4  import;
5  import;
6  import;
7  import;
9  public class Example1 {
10     public static void main(String[] args) throws IOException {
11         File inputFile = new File("Cir 613-22.pdf");
12         File outputFile = new File("Cir 613-22.pdf.gzip");
13         byte[] buffer = new byte[1024];
14         try(FileInputStream fis = new FileInputStream(inputFile);
15             FileOutputStream fos = new FileOutputStream(outputFile);
16             GZIPOutputStream gos = new GZIPOutputStream(fos)) {
17             int bytesRead =;
18             while(bytesRead != -1) {
19                 gos.write(buffer, 0, bytesRead);
20                 bytesRead =;
21             }
22             gos.finish();
23         }
24     }
25 }

In the above code, at line 11 and 12, I created an input file “Cir 613-22.pdf” and output file “Cir 613-22.pdf.gzip”.

At line 13, I have created a buffer of length 1024 bytes. This buffer will store the bytes read from the input stream.

Next in the try catch block, I have created an input stream “fis” from input file and output stream “gos”.

The output stream “gos” is wrapped around another output stream “fos” which is created from the output file.

At line 17, I read the file using the “read” method and pass the buffer as a parameter.

The read method will populate the buffer and returns the number of bytes read which is stored in variable “bytesRead”

Next in a loop, we write the data stored in the buffer to output stream “gos” and then we continue reading from the input stream.

This loop will continue until the bytesRead is -1.

Once the control exits from the loop, at line 22, we call “finish” method of output stream “gos” to end the writing.

In this way we compress a single file in gzip format.

Leave a Reply