how-to

File & Directory

How to compress files into ZIP archive

For this example you need:

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

This example shows how compress two files into ZIP archive:

try {
  /* -- zip destination file */>

  ZipOutputStream out = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream( "c:\\output.zip" ) ) );

  /* -- define buffer */

  BufferedInputStream origin = null;
  int BUFFER = 2048;
  byte data[] = new byte[ BUFFER ];

  /* -- list of source files for zip */
  String[] files = { "c:\\save.txt", "c:\\save1.txt" };

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

  /* -- check if source file exists */

  if ( ! new File( files[i] ).exists() ) continue;

    /* -- open file for adding to zip */

    FileInputStream fi = new FileInputStream( files[i] );
    origin = new BufferedInputStream( fi, BUFFER );

    /* -- start zip file writing */

    ZipEntry entry = new ZipEntry( new File( files[i] ).getName() );
    out.putNextEntry( entry );

    int count;
    while ( ( count = origin.read( data, 0, BUFFER ) ) != -1 ) {
      out.write( data, 0, count );
    }

    out.closeEntry();

    /* -- close file */

    origin.close();
  }

  /* -- close created zip file */

  out.close();
}
catch ( FileNotFoundException ex ) {
  Logger.getLogger( Window.class.getName()).log(Level.SEVERE, null, ex );
}
catch ( IOException ex) {
  Logger.getLogger( Window.class.getName()).log(Level.SEVERE, null, ex );
}

That example will create file c:\output.zip.

NOTE: Name for java.util.zip.ZipEntry() constructor must be without path - add only file name here. When you keep all path here, Windows default .zip decompressor will have a problem to show contained files.