KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > meshcms > util > ZipArchiver


1 /*
2  * MeshCMS - A simple CMS based on SiteMesh
3  * Copyright (C) 2004-2007 Luciano Vernaschi
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program 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
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  *
19  * You can contact the author at http://www.cromoteca.com
20  * and at info@cromoteca.com
21  */

22
23 package org.meshcms.util;
24
25 import java.io.*;
26 import java.util.zip.*;
27
28 /**
29  * Creates a ZIP file from a directory or file.
30  */

31 public class ZipArchiver extends DirectoryParser {
32   private ZipOutputStream zout;
33   private byte[] buf;
34
35   /**
36    * Instantiates the archiver for the given file and output stream.
37    *
38    * @param contents the file to be archieved
39    * @param out the OutputStream to write the archive to.
40    */

41   public ZipArchiver(File contents, OutputStream out) {
42     zout = new ZipOutputStream(out);
43     setInitialDir(contents);
44     setRecursive(true);
45     buf = new byte[Utils.BUFFER_SIZE];
46   }
47
48   protected boolean preProcessDirectory(File file, Path path) {
49     try {
50       ZipEntry ze = new ZipEntry(path + "/");
51       ze.setTime(file.lastModified());
52       zout.putNextEntry(ze);
53       zout.closeEntry();
54     } catch (IOException ex) {
55       ex.printStackTrace();
56       return false;
57     }
58
59     return true;
60   }
61
62   protected void processFile(File file, Path path) {
63     try {
64       ZipEntry ze = new ZipEntry(path.isRoot() ? file.getName() : path.toString());
65       ze.setTime(file.lastModified());
66       ze.setSize(file.length());
67       zout.putNextEntry(ze);
68       FileInputStream fis = new FileInputStream(file);
69       int len;
70
71       while((len = fis.read(buf)) != -1) {
72         zout.write(buf, 0, len);
73       }
74
75       fis.close();
76       zout.closeEntry();
77     } catch (IOException ex) {
78       ex.printStackTrace();
79     }
80   }
81
82   protected void postProcess() {
83     try {
84       zout.finish();
85       zout.flush();
86     } catch (IOException ex) {
87       ex.printStackTrace();
88     }
89   }
90 }
91
Popular Tags