01: /*
02: * ZipUtil.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.util;
13:
14: import java.io.File;
15: import java.io.FileInputStream;
16: import java.io.IOException;
17: import java.io.InputStream;
18: import java.util.ArrayList;
19: import java.util.Enumeration;
20: import java.util.List;
21: import java.util.zip.ZipEntry;
22: import java.util.zip.ZipFile;
23:
24: /**
25: * @author support@sql-workbench.net
26: */
27: public class ZipUtil {
28:
29: /**
30: * Test if the given File is a ZIP Archive.
31: * @param f the File to test
32: * @return true if the file is a ZIP Archive, false otherwise
33: */
34: public static boolean isZipFile(File f) {
35: // The JVM crashes (sometimes) if I pass my "fake" ClipboardFile object
36: // to the ZipFile constructor, so this is checked beforehand
37: if (f instanceof ClipboardFile)
38: return false;
39:
40: if (!f.exists())
41: return false;
42:
43: boolean isZip = false;
44:
45: InputStream in = null;
46: try {
47: in = new FileInputStream(f);
48: byte[] buffer = new byte[4];
49: int bytes = in.read(buffer);
50: if (bytes == 4) {
51: isZip = (buffer[0] == 'P' && buffer[1] == 'K');
52: isZip = isZip && (buffer[2] == 3 && buffer[3] == 4);
53: }
54: } catch (Throwable e) {
55: isZip = false;
56: } finally {
57: try {
58: in.close();
59: } catch (Throwable th) {
60: }
61: }
62: return isZip;
63: }
64:
65: /**
66: * Get the directory listing of a zip archive.
67: * Sub-Directories are not scanned.
68: *
69: * @param archive
70: * @return a list of filenames contained in the archive
71: */
72: public static List<String> getFiles(File archive)
73: throws IOException {
74: ZipFile zip = new ZipFile(archive);
75: List<String> result = new ArrayList<String>(zip.size());
76:
77: try {
78: Enumeration<? extends ZipEntry> entries = zip.entries();
79: while (entries.hasMoreElements()) {
80: ZipEntry entry = entries.nextElement();
81: result.add(entry.getName());
82: }
83: } finally {
84: zip.close();
85: }
86: return result;
87: }
88: }
|