Articles Directory

  • 0

How to Decompress a GZIP File in Java example

In the previous tutorial we saw how to compress a File with the GZIP method. In this tutorial we are going to see how to decompress the File that was compressed with the GZIP method.

Basically all you have to do to decompress a gzipped file is:

  • Create a FileInputStream to the compressed File.
  • Create a GZIPInputStream to the above FileInputStream.
  • Create a FileOutputStream to the decompressed File.
  • Read the bytes from the compressed File using the GZIPInputStream and write them to the uncompressed File.

Let’s take a look at the code snippet that follows:

package com.hafana.java.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressFileGzip {

	public static void main(String[] args) {

		String gzip_filepath = "C:\\Users\\nikos7\\Desktop\\files\\test.gzip";
		String decopressed_filepath = "C:\\Users\\nikos7\\Desktop\\files\\test2.txt";

		CompressFileGzip gZipFile = new CompressFileGzip();

		gZipFile.unGunzipFile(gzip_filepath, decopressed_filepath);
	}

	public void unGunzipFile(String compressedFile, String decompressedFile) {

		byte[] buffer = new byte[1024];

		try {

			FileInputStream fileIn = new FileInputStream(compressedFile);

			GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);

			FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);

			int bytes_read;

			while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {

				fileOutputStream.write(buffer, 0, bytes_read);
			}

			gZIPInputStream.close();
			fileOutputStream.close();

			System.out.println("The file was decompressed successfully!");

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}

 

loading...

Related posts

Related posts