KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > io > ZipUtil


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.io;
4
5 import java.io.File JavaDoc;
6 import java.io.FileOutputStream JavaDoc;
7 import java.io.IOException JavaDoc;
8 import java.io.InputStream JavaDoc;
9 import java.io.OutputStream JavaDoc;
10 import java.util.Enumeration JavaDoc;
11 import java.util.zip.ZipEntry JavaDoc;
12 import java.util.zip.ZipFile JavaDoc;
13
14 /**
15  * Performs zip/unzip operations on files and directories.
16  * todo Add many zip/unzip methods and settings
17  */

18 public class ZipUtil {
19
20     // ---------------------------------------------------------------- zip
21

22     // ---------------------------------------------------------------- unzip
23

24
25     /**
26      * Unpacks a zip file to the target directory.
27      *
28      * @param zipFile zip file
29      * @param destDir destination directory
30      *
31      * @throws IOException
32      */

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