How do I decompress a GZip file in Java?

In the previous example we have learn how to compress a file in GZIP format. To get the file back to its original version we will now learn how to decompress the gzip file. Just like the previous example, we are also going to use the FileInputStream and FileOutputStream class to read the compressed source file and to write out the decompressed file. While GZipOutputStream was used to to create the gzip file, the GZipInputStream is the class that handles the decompression.

Here is your code snippet:



public class GZipDecompressExample {
    public static void main(String[] args) {
        // GZip input and output file.
        String sourceFile = "/Users/wsaryada/Temp/Data/pom.gz";
        String targetFile = "/Users/wsaryada/Temp/Data/pom.xml";

        try {
            // Create a file input stream to read the source file.
            FileInputStream fis = new FileInputStream(sourceFile);

            // Create a gzip input stream to decompress the source
            // file defined by the file input stream.
            GZIPInputStream gzis = new GZIPInputStream(fis);

            // Create a buffer and temporary variable used during the
            // file decompress process.
            byte[] buffer = new byte[1024];
            int length;

            // Create file output stream where the decompress result
            // will be stored.
            FileOutputStream fos = new FileOutputStream(targetFile);

            // Read from the compressed source file and write the
            // decompress file.
            while ((length = > 0) {
                fos.write(buffer, 0, length);

            // Close the resources.
        } catch (IOException e) {

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply