Saturday 6 April 2013

Compress Files into Zip Format


The java.util.zip package provides direct functionality to access zip files.

Below are the steps to follow for compressing files into zip file

1. create FileOutputStream
2. create ZipOutputStream using FileOutputStream
3. create a ZipEntry
4. add ZipEntry (individual files or directories) to ZipOutputStream
5. create a FileInputStream
6. write inputstream into zipoutputsteam (i.e. zipentry)
7. close inputstream
8. close zipentry
9. For multiple files continue from step 3
10. close outputstreams


The code for compressing the files into Zip file is provided below:

package testapp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author naveen.k
 */
public class ZipUtilityTest {

    public static void main(String[] args) {
        compressToZipFile();
    }

    public static void compressToZipFile(){
        int len = 0;
        byte[] buffer = new byte[1024];
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try{
            fos = new FileOutputStream("D:\\Test\\TestZip.zip");    // Not a good standard of providing name like this...
            zos = new ZipOutputStream(fos);

            ZipEntry entry1 = new ZipEntry("test1.log");
            zos.putNextEntry(entry1);

            fis = new FileInputStream("D:\\Test\\TestZipContent\\Message1.log");
            while((len = fis.read(buffer)) > 0){
                zos.write(buffer, 0, len);
            }
            fis.close();
            zos.closeEntry();

            ZipEntry entry2 = new ZipEntry("test2.log");
            zos.putNextEntry(entry2);

            fis = new FileInputStream("D:\\Test\\TestZipContent\\Message2.log");
            while((len = fis.read(buffer)) > 0){
                zos.write(buffer, 0, len);
            }
            fis.close();
            zos.closeEntry();

            zos.flush();
            zos.close();
            System.out.println("Done");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(fos != null)fos.close();
                if(zos != null)zos.close();
                if(fis != null)fis.close();
            }catch(Exception e){
            }
        }
    }
}

1 comment:

  1. Very useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
    kindle mobi formatting services

    ReplyDelete