Here you can find the source of doZip(String baseDir, String fileName)
@SuppressWarnings("rawtypes") public static void doZip(String baseDir, String fileName) throws Exception
//package com.java2s; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { @SuppressWarnings("rawtypes") public static void doZip(String baseDir, String fileName) throws Exception { List fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName)); ZipEntry ze = null;//from ww w . j a va2 s . c o m byte[] buf = new byte[1024]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File f = (File) fileList.get(i); ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); while ((readLen = is.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } is.close(); } zos.close(); } public static List<File> getSubFiles(File baseDir) { List<File> ret = new ArrayList<File>(); File[] tmp = baseDir.listFiles(); for (int i = 0; i < tmp.length; i++) { if (tmp[i].isFile()) ret.add(tmp[i]); if (tmp[i].isDirectory()) ret.addAll(getSubFiles(tmp[i])); } return ret; } private static String getAbsFileName(String baseDir, File realFileName) { File real = realFileName; File base = new File(baseDir); String ret = real.getName(); while (true) { real = real.getParentFile(); if (real == null) break; if (real.equals(base)) break; else ret = real.getName() + "/" + ret; } return ret; } }