/* * Copyright (c) 2007 Lalit Mehta * * 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. * */ package com.saiyam.zip.example; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; /** * Zip all the files of a folder

* * @author Lalit Mehta * */ public class ZipFile { public static void main(String[] args) { try { //name of zip file to create String outFilename = "c:/file.zip"; //create ZipOutputStream object ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); //path to the folder to be zipped File zipFolder = new File("E:/database"); //get path prefix so that the zip file does not contain the whole path // eg. if folder to be zipped is /home/lalit/test // the zip file when opened will have test folder and not home/lalit/test folder int len = zipFolder.getAbsolutePath().lastIndexOf(File.separator); String baseName = zipFolder.getAbsolutePath().substring(0,len+1); addFolderToZip(zipFolder, out, baseName); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } } }