ZipOutputStream Class To Compress Files in Zip Format

text zoom

Java 6 provide the utility classes for the compression and decompression which we have seen in the last page. The file java.util.zip.ZipOutputStream is provided by Java 6 to compress the files in the zip format. Zip is common format for Windows environment and is widely accepted in IT world. The below example will show how we can use the ZipOutputStream to compress the files in the zip format.


 



Example:-



Note:- The below example will except the file names as command line argument. Please provide the full path names for the file.









package com.visualbuilder;


import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.util.zip.Adler32;

import java.util.zip.CheckedOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;


public class ZipCompressionExample {

        public static void main(String[] args) {

           try{

                   FileOutputStream f = new FileOutputStream("C://test.zip");

                   CheckedOutputStream csum = new CheckedOutputStream( f, new Adler32());

                    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum));

                   out.setComment("Sample for zip compression technique");

                  for (int i = 0; i < args.length; i++) {

                        System.out.println("Writing file " + args[i]);

                        BufferedReader in = new BufferedReader(new FileReader(args[i]));

                        out.putNextEntry(new ZipEntry(args[i]));

                        int c;

                        while ((c = in.read()) != -1)

                                out.write(c);

                        in.close();

                       }

               out.close();

            }catch(Exception e){

                    e.printStackTrace();

           }

     }

}



 



Output:-



When the above program runs it will generate the test.zip file in C Drive. It contains all the files which is passed in the command line as arguments in compressed format.

                    

Copyright © 2012 VisualBuilder. All rights reserved