Here you can find the source of zipDirectory(File zipDir, ZipOutputStream zos)
Parameter | Description |
---|---|
zipDir | the directory to ZIP |
zos | the ZIP output stream |
Parameter | Description |
---|---|
IOException | if reading the directory or writing the ZIP streamfails |
public static void zipDirectory(File zipDir, ZipOutputStream zos) throws IOException
//package com.java2s; /*/*w w w .j av a 2 s. c om*/ * Copyright (c) 2012 Data Harmonisation Panel * * All rights reserved. This program and the accompanying materials are made * available under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * HUMBOLDT EU Integrated Project #030962 * Data Harmonisation Panel <http://www.dhpanel.eu> */ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /** * ZIP a directory with sub-folders and write it to the given output stream. * * @param zipDir the directory to ZIP * @param zos the ZIP output stream * @throws IOException if reading the directory or writing the ZIP stream * fails */ public static void zipDirectory(File zipDir, ZipOutputStream zos) throws IOException { zipDirectory(zipDir, zos, ""); } private static void zipDirectory(File zipDir, ZipOutputStream zos, String parentFolder) throws IOException { String[] dirList = zipDir.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; for (int i = 0; i < dirList.length; i++) { File f = new File(zipDir, dirList[i]); if (f.isDirectory()) { if (parentFolder.isEmpty()) zipDirectory(f, zos, f.getName()); else zipDirectory(f, zos, parentFolder + "/" + f.getName()); continue; } FileInputStream fis = new FileInputStream(f); ZipEntry anEntry; if (parentFolder.isEmpty()) anEntry = new ZipEntry(f.getName()); else anEntry = new ZipEntry(parentFolder + "/" + f.getName()); zos.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } fis.close(); } } }