Friday, August 12, 2016

Compress File Ke Dalam GZip Format Dalam Java

Berikut ini contoh program untuk memformat file kedalam GZip format, sebelumnya saya buat file yang terletak pada direktori C:\\ dengan n... thumbnail 1 summary

Berikut ini contoh program untuk memformat file kedalam GZip format, sebelumnya saya buat file yang terletak pada direktori C:\\ dengan nama newfile.txt "C:\\newfile.txt" yang akan kita kompress, berikut ini contoh programnya

Nama file : compress_File.java

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

public class compress_File {
   
  public static void main( String[] args )
  {
      compress_File cf = new compress_File();
      cf.compress_File();
  }

  public void compress_File(){
    byte[] buffer = new byte[1024];
    try{
      //Specify Name and Path of Output GZip file here
      GZIPOutputStream gos =
       new GZIPOutputStream(new FileOutputStream("C://newfile.gz"));

      //Specify location of Input file here
      FileInputStream fis =
       new FileInputStream("C://newfile.txt");

      //Reading from input file and writing to output GZip file
      int length;
      while ((length = fis.read(buffer)) > 0) {

        /* public void write(byte[] buf, int off, int len):
         * Writes array of bytes to the compressed output stream.
         * This method will block until all the bytes are written.
         * Parameters:
         * buf - the data to be written
         * off - the start offset of the data
         * len - the length of the data
         */
        gos.write(buffer, 0, length);
      }

      fis.close();

      /* public void finish(): Finishes writing compressed
       * data to the output stream without closing the
       * underlying stream.
       */
      gos.finish();
      gos.close();

      System.out.println("File Compressed!!");

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

Output


program dibuat menggunakan netbeans
selamat mencoba semoga bermanfaat ...

No comments

Post a Comment