1 5 package ve.luz.ica.util; 6 7 import java.io.BufferedInputStream ; 8 import java.io.BufferedReader ; 9 import java.io.File ; 10 import java.io.FileOutputStream ; 11 import java.io.IOException ; 12 import java.io.InputStream ; 13 import java.io.InputStreamReader ; 14 import java.io.Reader ; 15 import java.util.Enumeration ; 16 import java.util.zip.ZipEntry ; 17 import java.util.zip.ZipFile ; 18 19 import org.apache.commons.logging.Log; 20 import org.apache.commons.logging.LogFactory; 21 22 26 public final class ZipUtil 27 { 28 private static final Log LOG = LogFactory.getLog(ZipUtil.class); 29 30 private static final int BUFFER_SIZE = 2048; 31 32 35 private ZipUtil() 36 { 37 } 38 39 46 public static InputStream getInputStream(String zipFileName, String entryName) throws IOException 47 { 48 if (LOG.isDebugEnabled()) LOG.debug("Zip file name " + zipFileName); 49 ZipFile zip = new ZipFile (zipFileName); 50 ZipEntry entry = zip.getEntry(entryName); 51 InputStream is = new BufferedInputStream (zip.getInputStream(entry)); 52 53 return is; 54 } 55 56 63 public static Reader getReader(String zipFileName, String entryName) throws IOException 64 { 65 InputStream is = getInputStream(zipFileName, entryName); 66 return new BufferedReader (new InputStreamReader (is), BUFFER_SIZE); 67 } 68 69 79 public static String extractFiles(String zipFileName, String targetDir, String prefix) throws IOException 80 { 81 ZipFile zipFile = new ZipFile (zipFileName); 82 File targetDirFile = new File (targetDir); 83 return extractFiles(zipFile, targetDirFile, prefix); 84 } 85 86 87 97 public static String extractFiles(ZipFile zipFile, File targetDir, String prefix) throws IOException 98 { 99 if (LOG.isDebugEnabled()) LOG.debug("unzipping file " + zipFile.getName()); 100 101 103 Enumeration entries = zipFile.entries(); 104 while (entries.hasMoreElements()) 105 { 106 ZipEntry entry = (ZipEntry ) entries.nextElement(); 107 String entryName = entry.getName(); 108 109 if ((prefix == null) || entryName.startsWith(prefix)) 110 { 111 if (LOG.isDebugEnabled()) LOG.debug("unzipping " + entry.getName()); 112 113 File file = new File (targetDir, entryName); 114 if (entry.isDirectory()) 115 { 116 file.mkdirs(); 117 } 118 else 119 { 120 InputStream in = zipFile.getInputStream(entry); 121 FileOutputStream out = new FileOutputStream (file); 122 123 byte[] b = new byte[BUFFER_SIZE]; 124 int len = in.read(b); 125 while (len != -1) 126 { 127 out.write(b, 0, len); 128 len = in.read(b); 129 } 130 out.close(); 131 in.close(); 132 } 133 } 134 } 135 136 return targetDir.getPath(); 137 } 138 } 139 | Popular Tags |