KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > portlet > util > FolderArchiver


1 package com.opensymphony.webwork.portlet.util;
2
3 import java.io.File JavaDoc;
4 import java.io.FileInputStream JavaDoc;
5 import java.io.FileOutputStream JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.util.zip.ZipEntry JavaDoc;
8 import java.util.zip.ZipOutputStream JavaDoc;
9
10 public class FolderArchiver {
11     private static final int BUFFER_SIZE = 10240;
12
13     private File JavaDoc folderToArchive;
14
15     private File JavaDoc archiveFile;
16
17     public FolderArchiver(File JavaDoc folderToArchive, File JavaDoc archiveFile) {
18         this.folderToArchive = folderToArchive;
19         this.archiveFile = archiveFile;
20     }
21
22     public void doArchive() throws Exception JavaDoc {
23         FileOutputStream JavaDoc stream = new FileOutputStream JavaDoc(archiveFile);
24         ZipOutputStream JavaDoc output = new ZipOutputStream JavaDoc(stream);
25         compressFile(folderToArchive, output);
26         output.close();
27         stream.close();
28     }
29
30     private void compressFile(File JavaDoc file, ZipOutputStream JavaDoc output) throws IOException JavaDoc {
31         if (file == null || !file.exists())
32             return;
33         if (file.isFile() && !file.equals(archiveFile)) {
34             byte buffer[] = new byte[10240];
35             String JavaDoc path = file.getPath().substring(folderToArchive.getPath().length());
36             path = path.replaceAll("\\\\", "/");
37             if (path.length() > 0 && path.charAt(0) == '/')
38                 path = path.substring(1);
39             ZipEntry JavaDoc entry = new ZipEntry JavaDoc(path);
40             entry.setTime(file.lastModified());
41             output.putNextEntry(entry);
42             FileInputStream JavaDoc in = new FileInputStream JavaDoc(file);
43             int data;
44             while ((data = in.read(buffer, 0, buffer.length)) > 0) output.write(buffer, 0, data);
45             in.close();
46         } else if (file.isDirectory()) {
47             File JavaDoc files[] = file.listFiles();
48             for (int i = 0; i < files.length; i++)
49                 compressFile(files[i], output);
50
51         }
52     }
53
54 }
55
56
Popular Tags