Sunday, January 13, 2013
Today I am going to post a program that will be able to compress any file in GZIP format. Java language can be used very efficiently for this purpose. There is a special package java.util.zip which contains several classes that can be used for compressing files and folders. Today I am going to deal with GZIPOutputStream . This particular class is used to produce with a file in compressed GZIP format with extension .gz . Here at first the file to be compressed is taken as input from user. Then FileInputStream is used to open a stream connecting to that file. Next the data from file is read in a buffer of capacity 4K. Then the buffer is written to the output stream. Here output stream is nothing but a FileOutputStream wrapped over with a GZIPOutputStream . This process of reading and writing goes on until end of file is reached.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

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

public class CompressFile {
  public void gzipFile(String from, String to) throws IOException {
    FileInputStream in = new FileInputStream(from);  //stream to input file
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));  //stream to output file
    byte[] buffer = new byte[4096];  //defining buffer capacity
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1)  //reading into buffer
      out.write(buffer, 0, bytesRead);  //writing buffer contents to output stream
    in.close();  //closing both streams
    out.close();
  }

  public static void main(String args[]) throws IOException {
  if(args.length>0){
        String from=args[0];  //getting source file as command line input
        new CompressFile().gzipFile(from,from+".gz");
  }
  }
}
NOTE : Very soon I will be posting a GUI version of this ptogram.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared

1 comment:

  1. I really appreciate your efforts in java programming and the codes in your blog. You are great.
    Please I need your help on DCT Steganography code. (i.e hinding and extracting files in a jpeg image.).
    Thank you.
    Raphael
    amb_raph@yahoo.com.

    ReplyDelete

Total Pageviews

Followers


Labels

Popular Posts

free counters