KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > file > ZipUtil


1 package jodd.file;
2
3 import java.io.BufferedOutputStream;
4 import java.io.File;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9 import java.util.Enumeration;
10 import java.util.zip.ZipEntry;
11 import java.util.zip.ZipFile;
12
13 import jodd.util.Util;
14
15 /**
16  * Performs zip/unzip operations on files and directories.
17  */

18
19 public class ZipUtil {
20
21     /**
22      * Unpacks a zip file to the target directory.
23      *
24      * @param zipFile zip file
25      * @param destDir destination directory
26      *
27      * @throws IOException
28      */

29     public static void unzip(File zipFile, File destDir) throws IOException {
30         ZipFile zip = new ZipFile(zipFile);
31         Enumeration en = zip.entries();
32         int bufSize = 8196;
33
34         while (en.hasMoreElements()) {
35             ZipEntry entry = (ZipEntry) en.nextElement();
36             File file = (destDir != null) ? new File(destDir, entry.getName()) : new File(entry.getName());
37             if (entry.isDirectory()) {
38                 if (!file.mkdirs()) {
39                     if (file.isDirectory() == false) {
40                         throw new IOException("Error creating directory: " + file);
41                     }
42                 }
43             } else {
44                 File parent = file.getParentFile();
45                 if (parent != null && !parent.exists()) {
46                     if (!parent.mkdirs()) {
47                         if (file.isDirectory() == false) {
48                             throw new IOException("Error creating directory: " + parent);
49                         }
50                     }
51                 }
52
53                 InputStream in = zip.getInputStream(entry);
54                 try {
55                     OutputStream out = new BufferedOutputStream(new FileOutputStream(file), bufSize);
56                     try {
57                         Util.copyPipe(in, out, bufSize);
58                     } finally {
59                         out.close();
60                     }
61                 } finally {
62                     in.close();
63                 }
64             }
65         }
66     }
67
68 }
69
Popular Tags