001/** 002 * 003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. 004 * 005 * This library is free software; you can redistribute it and/or 006 * modify it under the terms of the GNU Lesser General Public 007 * License as published by the Free Software Foundation; either 008 * version 2.1 of the License, or (at your option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013 * Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public 016 * License along with this library. If not, see <http://www.gnu.org/licenses/>. 017 * 018 **/ 019package lucee.loader.util; 020 021import java.io.File; 022import java.io.FileInputStream; 023import java.io.FileOutputStream; 024import java.io.IOException; 025import java.io.InputStream; 026import java.util.zip.ZipEntry; 027import java.util.zip.ZipOutputStream; 028 029public class ZipUtil { 030 031 public static void zip(File src, File trgZipFile) throws IOException { 032 if(trgZipFile.isDirectory()) throw new IllegalArgumentException("argument trgZipFile is the name of a existing directory"); 033 034 035 ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(trgZipFile)); 036 try{ 037 if(src.isFile()) 038 addEntries(zos,src.getParentFile(),src); 039 else if(src.isDirectory()) 040 addEntries(zos,src,src.listFiles()); 041 } 042 finally { 043 Util.closeEL(zos); 044 } 045 } 046 047 private static void addEntries(ZipOutputStream zos, File root, File... files) throws IOException { 048 if(files!=null)for (File file : files) { 049 050 // directory 051 if(file.isDirectory()) { 052 addEntries(zos, root, file.listFiles()); 053 continue; 054 } 055 if(!file.isFile()) continue; 056 057 // file 058 InputStream is=null; 059 ZipEntry ze = generateZipEntry(root,file); 060 061 try { 062 zos.putNextEntry(ze); 063 Util.copy(is=new FileInputStream(file),zos,false,false); 064 } 065 finally { 066 Util.closeEL(is); 067 zos.closeEntry(); 068 } 069 } 070 } 071 072 private static ZipEntry generateZipEntry(File root, File file) { 073 String strRoot=root.getAbsolutePath(); 074 String strFile=file.getAbsolutePath(); 075 return new ZipEntry(strFile.substring(strRoot.length() + 1, strFile.length())); 076 077 } 078}