Here you can find the source of zip(final File dir, final File target)
public static void zip(final File dir, final File target) throws IOException
//package com.java2s; /****************************************************************************** * Copyright (c) 2010 Oracle//from w w w. jav a2 s. co m * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Konstantin Komissarchik - initial implementation and ongoing maintenance ******************************************************************************/ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { public static void zip(final File dir, final File target) throws IOException { if (target.exists()) { delete(target); } final ZipOutputStream zip = new ZipOutputStream( new FileOutputStream(target)); try { zipDir(target, zip, dir, ""); //$NON-NLS-1$ } finally { try { zip.close(); } catch (IOException e) { } } } private static void delete(final File f) throws IOException { if (f.isDirectory()) { for (File child : f.listFiles()) { delete(child); } } if (!f.delete()) { final String msg = "Could not delete " + f.getPath() + "."; //$NON-NLS-1$ //$NON-NLS-2$ throw new IOException(msg); } } private static void zipDir(final File target, final ZipOutputStream zip, final File dir, final String path) throws IOException { for (File f : dir.listFiles()) { final String cpath = path + f.getName(); if (f.isDirectory()) { zipDir(target, zip, f, cpath + "/"); //$NON-NLS-1$ } else { zipFile(target, zip, f, cpath); } } } private static void zipFile(final File target, final ZipOutputStream zip, final File file, final String path) throws IOException { if (!file.equals(target)) { final ZipEntry ze = new ZipEntry(path); ze.setTime(file.lastModified() + 1999); ze.setMethod(ZipEntry.DEFLATED); zip.putNextEntry(ze); final FileInputStream in = new FileInputStream(file); try { int bufsize = 8 * 1024; final long flength = file.length(); if (flength == 0) { return; } else if (flength < bufsize) { bufsize = (int) flength; } final byte[] buffer = new byte[bufsize]; int count = in.read(buffer); while (count != -1) { zip.write(buffer, 0, count); count = in.read(buffer); } } finally { try { in.close(); } catch (IOException e) { } } } } }