Share on Google+Share on Google+

How to make a zip file in java

Advertisement
This tutorial discusses the example code of creating a zip file in Java.

Description:

In this example we will discuss about how to create zip file from the text file. In the following code  ZipOutputStream class from java.util.zip package is used. The ZipOutputStream class provides the methods to create zip file.

Code:

import java.io.*;
import java.util.zip.*;
import java.io.FileInputStream.*;
import java.util.zip.ZipOutputStream.*;


public class ZipDemo {
  public static void main(String[] args) {
    try {
      FileInputStream fin = new FileInputStream("unzipfile.txt");
      BufferedInputStream zipin = new BufferedInputStream(fin);
      FileOutputStream fout = new FileOutputStream("zipfile.zip");
      BufferedOutputStream bout = new BufferedOutputStream(fout);
      ZipOutputStream zipout = new ZipOutputStream(bout);
      byte[] data = new byte[1000];
      int count;
      zipout.putNextEntry(new ZipEntry("zipfile.zip"));
      while ((count = zipin.read(data, 01000)) != -1) {
        zipout.write(data, 0, count);
      }
      zipin.close();
      zipout.close();
      System.out.println("File SuccessFully converted In Zip Format");
    catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}

Output:

When you compile and run this program it will create the zip (zipfile.zip ) of unzipfile.txt file

Advertisements

Advertisement

Posted on: July 7, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.