Zip a file


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

public class Main {
  public static void main(String[] args) throws Exception {
    doZip("a.txt", "a.zip");
  }

  public static void doZip(String filename, String zipfilename)throws Exception {
    byte[] buf = new byte[1024];
    FileInputStream fis = new FileInputStream(filename);
    fis.read(buf, 0, buf.length);

    CRC32 crc = new CRC32();
    ZipOutputStream s = new ZipOutputStream(
        (OutputStream) new FileOutputStream(zipfilename));
    s.setLevel(6);

    ZipEntry entry = new ZipEntry(filename);
    entry.setSize((long) buf.length);
    crc.reset();
    crc.update(buf);
    entry.setCrc(crc.getValue());
    s.putNextEntry(entry);
    s.write(buf, 0, buf.length);
    s.finish();
    s.close();
    
    fis.close();
  }
}
Home 
  Java Book 
    Runnable examples  

Zip File:
  1. List the contents of a zip file
  2. Compress a Byte Array
  3. Zip a file
  4. Zip a directory including its subdirectories recursively
  5. Decompress(unzip) a Byte Array