Java tutorial
//package com.java2s; /* * JGrass - Free Open Source Java GIS http://www.jgrass.org * (C) HydroloGIS - www.hydrologis.com * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Library General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more * details. * * You should have received a copy of the GNU Library General Public License * along with this library; if not, write to the Free Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA */ 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 { static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip, boolean addFolder) throws IOException { File folder = new File(srcFolder); String listOfFiles[] = folder.list(); for (int i = 0; i < listOfFiles.length; i++) { String folderPath = null; if (path.length() < 1) { folderPath = folder.getName(); } else { folderPath = path + File.separator + folder.getName(); } String srcFile = srcFolder + File.separator + listOfFiles[i]; addToZip(folderPath, srcFile, zip); } } static private void addToZip(String path, String srcFile, ZipOutputStream zip) throws IOException { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip, true); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = null; try { in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + File.separator + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }