01: /*
02: * CoadunationLib: The coaduntion implementation library.
03: * Copyright (C) 2006 Rift IT Contracting
04: *
05: * This library is free software; you can redistribute it and/or
06: * modify it under the terms of the GNU Lesser General Public
07: * License as published by the Free Software Foundation; either
08: * version 2.1 of the License, or (at your option) any later version.
09: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library; if not, write to the Free Software
17: * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18: *
19: * JarUtil.java
20: *
21: * This class supplies methods to interact with a jar file.
22: */
23:
24: // package path
25: package com.rift.coad.lib.common;
26:
27: // java imports
28: import com.rift.coad.lib.common.*;
29: import java.io.InputStream;
30: import java.io.FileOutputStream;
31: import java.io.File;
32: import java.util.Enumeration;
33: import java.util.jar.JarFile;
34: import java.util.jar.JarEntry;
35:
36: /**
37: * This class supplies methods to interact with a jar file.
38: *
39: * @author Brett Chaldecott
40: */
41: public class JarUtil {
42:
43: /**
44: * Private constructor to prevent instanciation of this object.
45: */
46: private JarUtil() {
47: }
48:
49: /**
50: * This method extracts the contents of a source file to a destination file.
51: *
52: * @param source The source file to extract.
53: * @param destination The destination file to extract.
54: */
55: public static void extract(File source, File destination)
56: throws CommonException {
57: try {
58: JarFile jarFile = new JarFile(source);
59: Enumeration entries = jarFile.entries();
60: byte[] readBuffer = new byte[1024];
61: while (entries.hasMoreElements()) {
62: JarEntry entry = (JarEntry) entries.nextElement();
63: File path = new File(destination + File.separator
64: + entry.getName());
65: if (entry.isDirectory()) {
66: if (!path.mkdirs()) {
67: throw new CommonException(
68: "Failed to create the dir ["
69: + path.getAbsolutePath() + "]");
70: }
71: continue;
72: }
73: InputStream inputStream = jarFile.getInputStream(entry);
74: FileOutputStream outputStream = new FileOutputStream(
75: path);
76: int readBytes = 0;
77: while ((readBytes = inputStream.read(readBuffer, 0,
78: readBuffer.length)) != -1) {
79: outputStream.write(readBuffer, 0, readBytes);
80: }
81: outputStream.flush();
82: inputStream.close();
83: outputStream.close();
84: }
85: } catch (Exception ex) {
86: throw new CommonException("Failed to extract the file ["
87: + source.getAbsolutePath() + "] to ["
88: + destination.getAbsolutePath() + "] because :"
89: + ex.getMessage(), ex);
90: }
91: }
92: }
|