Here you can find the source of zip(String sourceDir, String zipFile)
public static void zip(String sourceDir, String zipFile) throws Exception
//package com.java2s; /*Copyright (C) 2012 Crow Hou (crow_hou@126.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { public static void zip(String sourceDir, String zipFile) throws Exception { ZipOutputStream zos = null; try {//from w w w .ja va 2s . c o m zos = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(zipFile))); File file = new File(sourceDir); String basePath = null; if (file.isDirectory()) { basePath = file.getPath(); } else { basePath = file.getParent(); } zipFile(file, basePath, zos); } finally { if (zos != null) { try { zos.closeEntry(); } catch (IOException e) { // donothing } try { zos.flush(); zos.close(); } catch (IOException e) { // do nothing } } } } /** * * create date:2009- 6- 9 author:Administrator * * @param source * @param basePath * @param zos * @throws IOException */ private static void zipFile(File source, String basePath, ZipOutputStream zos) throws Exception { File[] files = null; if (source.isDirectory()) { files = source.listFiles(); } else { files = new File[1]; files[0] = source; } String pathName; byte[] buf = new byte[1024]; int length = 0; for (File file : files) { if (file.isDirectory()) { pathName = file.getPath().substring(basePath.length() + 1) + "/"; zos.putNextEntry(new ZipEntry(pathName)); zipFile(file, basePath, zos); } else { pathName = file.getPath().substring(basePath.length() + 1); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); zos.putNextEntry(new ZipEntry(pathName)); while ((length = is.read(buf)) != -1) { zos.write(buf, 0, length); } } finally { is.close(); } } } } }