PageRenderTime 73ms CodeModel.GetById 41ms app.highlight 12ms RepoModel.GetById 18ms app.codeStats 0ms

/src/mpv5/utils/files/UnZip.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 189 lines | 111 code | 15 blank | 63 comment | 20 complexity | 042766e6864c09d37f0540230e1c963c MD5 | raw file
  1/*
  2 * 
  3 * 
  4 */
  5package mpv5.utils.files;
  6
  7/**
  8 *
  9 * @author
 10 */
 11import java.io.File;
 12import java.io.FileOutputStream;
 13import java.io.IOException;
 14import java.io.InputStream;
 15import java.util.Enumeration;
 16import java.util.SortedSet;
 17import java.util.TreeSet;
 18import java.util.zip.ZipEntry;
 19import java.util.zip.ZipFile;
 20import mpv5.logging.Log;
 21
 22/**
 23 * UnZip -- print or unzip a JAR or PKZIP file using java.util.zip. Command-line
 24 * version: extracts files.
 25 * 
 26 * @author Ian Darwin, Ian@DarwinSys.com $Id: UnZip.java,v 1.7 2004/03/07
 27 *         17:40:35 ian Exp $
 28 */
 29public class UnZip {
 30
 31    /** Constants for mode listing or mode extracting. */
 32    public static final int LIST = 0, EXTRACT = 1;
 33    /** Whether we are extracting or just printing TOC */
 34    protected int mode = LIST;
 35    /** The ZipFile that is used to read an archive */
 36    private ZipFile zippy;
 37    /** The buffer for reading/writing the ZipFile data */
 38    protected byte[] b;
 39    private String path;
 40
 41    /**
 42     * Construct an UnZipper, process each .ZIP file from
 43     * zipFiles through that object.
 44     * @param zipfiles
 45     * @param toDir 
 46     */
 47    public static void deflate(String zipfiles, String toDir) {
 48        File fil = new File(toDir);
 49        if (fil.isDirectory()) {
 50            fil.mkdirs();
 51        } else {
 52            fil.getParentFile().mkdirs();
 53        }
 54
 55        UnZip u = new UnZip();
 56        u.setPath(toDir);
 57        u.setMode(EXTRACT);
 58
 59        String candidate = zipfiles;
 60        Log.Debug(UnZip.class, "Trying path " + candidate);
 61        if (candidate.endsWith(".zip") || candidate.endsWith(".jar")) {
 62            u.unZip(candidate);
 63        } else {
 64            Log.Debug(UnZip.class, "Not a zip file? " + candidate);
 65        }
 66    }
 67
 68    /** Construct an UnZip object. Just allocate the buffer */
 69    UnZip() {
 70        b = new byte[8092];
 71    }
 72
 73    /** Set the Mode (list, extract).
 74     * @param m 
 75     */
 76    protected void setMode(int m) {
 77        if (m == LIST || m == EXTRACT) {
 78            mode = m;
 79        }
 80    }
 81    /** Cache of paths we've mkdir()ed. */
 82    protected SortedSet dirsMade;
 83
 84    /** For a given Zip file, process each entry.
 85     * @param fileName 
 86     */
 87    public void unZip(String fileName) {
 88        dirsMade = new TreeSet();
 89        try {
 90            zippy = new ZipFile(fileName);
 91            Enumeration all = getZippy().entries();
 92            while (all.hasMoreElements()) {
 93                getFile((ZipEntry) all.nextElement());
 94            }
 95        } catch (IOException err) {
 96            Log.Debug(UnZip.class, "IO Error: " + err);
 97            return;
 98        }
 99    }
100    protected boolean warnedMkDir = false;
101
102    /**
103     * Process one file from the zip, given its name. Either print the name, or
104     * create the file on disk.
105     * @param e
106     * @throws java.io.IOException 
107     */
108    @SuppressWarnings("unchecked")
109    protected void getFile(ZipEntry e) throws IOException {
110        String zipName = getPath() + File.separator + e.getName();
111
112
113        switch (mode) {
114            case EXTRACT:
115//                if (zipName.startsWith("/")) {
116//                    if (!warnedMkDir) {
117//                        System.out.println("Ignoring absolute paths");
118//                    }
119//                    warnedMkDir = true;
120//                    zipName = zipName.substring(1);
121//                }
122                // if a directory, just return. We mkdir for every file,
123                // since some widely-used Zip creators don't put out
124                // any directory entries, or put them in the wrong place.
125                if (zipName.endsWith("/")) {
126                    return;
127                }
128                // Else must be a file; open the file for output
129                // Get the directory part.
130                int ix = zipName.lastIndexOf('/');
131                if (ix > 0) {
132                    String dirName = zipName.substring(0, ix);
133                    if (!dirsMade.contains(dirName)) {
134                        File d = new File(dirName);
135                        // If it already exists as a dir, don't do anything
136                        if (!(d.exists() && d.isDirectory())) {
137                            // Try to create the directory, warn if it fails
138                            Log.Debug(UnZip.class, "Creating Directory: " + dirName);
139                            if (!d.mkdirs()) {
140                                Log.Debug(UnZip.class, "Warning: unable to mkdir " + dirName);
141                            }
142                            dirsMade.add(dirName);
143                        }
144                    }
145                }
146                Log.Debug(UnZip.class, "Creating " + zipName);
147                FileOutputStream os = new FileOutputStream(zipName);
148                InputStream is = getZippy().getInputStream(e);
149                int n = 0;
150                while ((n = is.read(b)) > 0) {
151                    os.write(b, 0, n);
152                }
153                is.close();
154                os.close();
155                break;
156            case LIST:
157                // Not extracting, just list
158                if (e.isDirectory()) {
159                    Log.Debug(UnZip.class, "Directory " + zipName);
160                } else {
161                    Log.Debug(UnZip.class, "File " + zipName);
162                }
163                break;
164            default:
165                throw new IllegalStateException("mode value (" + mode + ") bad");
166        }
167    }
168
169    /**
170     * @return the path
171     */
172    public String getPath() {
173        return path;
174    }
175
176    /**
177     * @param path the path to set
178     */
179    public void setPath(String path) {
180        this.path = path;
181    }
182
183    /**
184     * @return the zippy
185     */
186    public ZipFile getZippy() {
187        return zippy;
188    }
189}