How to Compress a File in GZIP format in Java?

Here is an example to explain how to compress a File in GZIP format in Java

  • First Example compress a file in GZIP
package com.nourit.javaIO;

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

public class FileCompressioninGZIP {

  private static final String GZIP_DEST_FILE = "D:/tmp/NOUR-IT.gz";
  private static final String SOURCE_FILE = "D:/tmp/NOUR-IT.txt";

  public static void main(String[] args) {
    byte[] buffer = new byte[1024];
    try {

      GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(new FileOutputStream(GZIP_DEST_FILE));
      FileInputStream fileInputStream = new FileInputStream(SOURCE_FILE);

      int len;
      while ((len = fileInputStream.read(buffer)) > 0) {
        gZIPOutputStream.write(buffer, 0, len);
      }
      fileInputStream.close();

      gZIPOutputStream.finish();
      gZIPOutputStream.close();

      System.out.println("Operation successful!");

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}
  • Second example compress a file in GZIP
package com.nourit.javaIO;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.io.FileUtils;

public class FileCompressioninGZIP1 {
  private static final String GZIP_DEST_FILE = "D:/tmp/NOUR-IT.gz";
  private static final String SOURCE_FILE = "D:/tmp/NOUR-IT.txt";

  public static void main(String[] args) {
    try {
      GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(new FileOutputStream(GZIP_DEST_FILE));
      File newFile = new File(SOURCE_FILE);
      byte[] data = FileUtils.readFileToByteArray(newFile);
      gZIPOutputStream.write(data, 0, data.length);
      
      gZIPOutputStream.finish();
      gZIPOutputStream.close();

      System.out.println("Operation successful!");

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

}

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*