1 6 7 package org.contineo.core; 8 9 import java.io.BufferedOutputStream ; 10 import java.io.File ; 11 import java.io.FileOutputStream ; 12 import java.io.InputStream ; 13 import java.util.Enumeration ; 14 15 import org.apache.log4j.Level; 16 import org.apache.log4j.Logger; 17 import org.apache.tools.zip.ZipEntry; 18 import org.apache.tools.zip.ZipFile; 19 24 public class ZipBean { 25 26 32 public static boolean unzip(String zipsource, String target) { 33 boolean result = true; 34 try { 35 if(!target.endsWith("/")) 36 target = target + "/"; 37 ZipFile zip = new ZipFile(zipsource); 38 Enumeration entries = zip.getEntries(); 39 40 while (entries.hasMoreElements()) { 41 ZipEntry entry = (ZipEntry) entries.nextElement(); 42 saveEntry(target, zip, entry); 43 } 44 45 zip.close(); 46 } 47 catch (Exception e) { 48 result = false; 49 logError(e.getMessage()); 50 } 51 return result; 52 } 53 54 61 public static boolean unzip(String zipsource, String target, String entry) { 62 boolean result = true; 63 try { 64 if(!target.endsWith("/")) 65 target = target + "/"; 66 ZipFile zip = new ZipFile(zipsource); 67 ZipEntry zipe = new ZipEntry(entry); 68 saveEntry(target, zip, zipe); 69 } 70 catch (Exception e) { 71 result = false; 72 logError(e.getMessage()); 73 } 74 return result; 75 } 76 77 83 private static void saveEntry(String target, ZipFile zip, ZipEntry entry) throws Exception { 84 String targetFileName = target + entry.getName(); 85 86 if (entry.isDirectory()) { 87 File dir = new File (targetFileName); 88 dir.mkdirs(); 89 } else { 90 File file = new File (targetFileName); 91 File dir = new File (file.getParent()); 92 dir.mkdirs(); 93 dir = null; 94 file = null; 95 96 InputStream in = zip.getInputStream(entry); 97 BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream (targetFileName)); 98 byte[] buffer = new byte[1024]; 99 int len; 100 while ((len = in.read(buffer)) > 0) { 101 bos.write(buffer, 0, len); 102 } 103 in.close(); 104 bos.close(); 105 } 106 } 107 108 private static void logError(String message) { 109 Logger logger = LoggingManager.getLogger(org.contineo.core.ZipBean.class); 110 if (logger.isEnabledFor(Level.ERROR)) 111 logger.error(message); 112 } 113 } 114 115 | Popular Tags |