KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > util > FileUtil


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.jbi.util;
18
19 import java.io.BufferedInputStream JavaDoc;
20 import java.io.BufferedOutputStream JavaDoc;
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.zip.ZipEntry JavaDoc;
30 import java.util.zip.ZipFile JavaDoc;
31 import java.util.zip.ZipOutputStream JavaDoc;
32
33 /**
34  * File utilities
35  *
36  * @version $Revision: 426415 $
37  */

38 public class FileUtil {
39     
40     /**
41      * Buffer size used when copying the content of an input stream to
42      * an output stream.
43      */

44     private static final int DEFAULT_BUFFER_SIZE = 4096;
45
46     /**
47      * Move a File
48      *
49      * @param src
50      * @param targetDirectory
51      * @throws IOException
52      */

53     public static void moveFile(File JavaDoc src, File JavaDoc targetDirectory) throws IOException JavaDoc {
54         if (!src.renameTo(new File JavaDoc(targetDirectory, src.getName()))){
55             throw new IOException JavaDoc("Failed to move " + src + " to " + targetDirectory);
56         }
57     }
58
59     /**
60      * Build a path- but do not create it
61      *
62      * @param parent
63      * @param subDirectory
64      * @return a File representing the path
65      */

66     public static File JavaDoc getDirectoryPath(File JavaDoc parent, String JavaDoc subDirectory) {
67         File JavaDoc result = null;
68         if (parent != null){
69             result = new File JavaDoc(parent, subDirectory);
70         }
71         return result;
72     }
73
74     /**
75      * Build a directory path - creating directories if neccesary
76      *
77      * @param file
78      * @return true if the directory exists, or making it was successful
79      */

80     public static boolean buildDirectory(File JavaDoc file) {
81         return file.exists() || file.mkdirs();
82     }
83
84     /**
85      * Copy in stream to an out stream
86      *
87      * @param in
88      * @param out
89      * @throws IOException
90      */

91     public static void copyInputStream(InputStream JavaDoc in, OutputStream JavaDoc out) throws IOException JavaDoc {
92         byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
93         int len;
94         while ((len = in.read(buffer)) >= 0) {
95             out.write(buffer, 0, len);
96         }
97         in.close();
98         out.close();
99     }
100
101     /**
102      * Unpack a zip file
103      *
104      * @param theFile
105      * @param targetDir
106      * @return the file
107      * @throws IOException
108      */

109     public static File JavaDoc unpackArchive(File JavaDoc theFile, File JavaDoc targetDir) throws IOException JavaDoc {
110         if (!theFile.exists()) {
111             throw new IOException JavaDoc(theFile.getAbsolutePath() + " does not exist");
112         }
113         if (!buildDirectory(targetDir)) {
114             throw new IOException JavaDoc("Could not create directory: " + targetDir);
115         }
116         ZipFile JavaDoc zipFile;
117         zipFile = new ZipFile JavaDoc(theFile);
118         for (Enumeration JavaDoc entries = zipFile.entries(); entries.hasMoreElements();) {
119             ZipEntry JavaDoc entry = (ZipEntry JavaDoc) entries.nextElement();
120             File JavaDoc file = new File JavaDoc(targetDir, File.separator + entry.getName());
121             // Take the sledgehammer approach to creating directories
122
// to work around ZIP's that incorrectly miss directories
123
if (!buildDirectory(file.getParentFile())) {
124                 throw new IOException JavaDoc("Could not create directory: " + file.getParentFile());
125             }
126             if (!entry.isDirectory()) {
127                 copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(file)));
128             } else {
129                 if (!buildDirectory(file)) {
130                     throw new IOException JavaDoc("Could not create directory: " + file);
131                 }
132             }
133         }
134         zipFile.close();
135         return theFile;
136     }
137
138     /**
139      * Unpack an archive from a URL
140      *
141      * @param url
142      * @param targetDir
143      * @return the file to the url
144      * @throws IOException
145      */

146     public static File JavaDoc unpackArchive(URL JavaDoc url, File JavaDoc targetDir) throws IOException JavaDoc {
147         if (!targetDir.exists()) {
148             targetDir.mkdirs();
149         }
150         InputStream JavaDoc in = new BufferedInputStream JavaDoc(url.openStream(), DEFAULT_BUFFER_SIZE);
151         // make sure we get the actual file
152
File JavaDoc zip = File.createTempFile("arc", ".zip", targetDir);
153         OutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(zip));
154         copyInputStream(in, out);
155         out.close();
156         return unpackArchive(zip, targetDir);
157     }
158
159     /**
160      * Validate that an archive contains a named entry
161      *
162      * @param theFile
163      * @param name
164      * @return true if the entry exists
165      * @throws IOException
166      */

167     public static boolean archiveContainsEntry(File JavaDoc theFile, String JavaDoc name) throws IOException JavaDoc {
168         boolean result = false;
169         ZipFile JavaDoc zipFile;
170         zipFile = new ZipFile JavaDoc(theFile);
171         for (Enumeration JavaDoc entries = zipFile.entries(); entries.hasMoreElements();) {
172             ZipEntry JavaDoc entry = (ZipEntry JavaDoc) entries.nextElement();
173             if (entry.getName().equals(name)) {
174                 result = true;
175                 break;
176             }
177         }
178         zipFile.close();
179         return result;
180     }
181
182     /**
183      * Create a unique directory within a directory 'root'
184      *
185      * @param rootDir
186      * @param seed
187      * @return unique directory
188      * @throws IOException
189      */

190     public synchronized static File JavaDoc createUniqueDirectory(File JavaDoc rootDir, String JavaDoc seed) throws IOException JavaDoc {
191         int index = seed.lastIndexOf('.');
192         if (index > 0) {
193             seed = seed.substring(0, index);
194         }
195         File JavaDoc result = null;
196         int count = 0;
197         while (result == null) {
198             String JavaDoc name = seed + "." + count + ".tmp";
199             File JavaDoc file = new File JavaDoc(rootDir, name);
200             if (!file.exists()) {
201                 file.mkdirs();
202                 result = file;
203             }
204             count++;
205         }
206         return result;
207     }
208
209     /**
210      * Delete a file
211      *
212      * @param fileToDelete
213      * @return true if the File is deleted
214      */

215     public static boolean deleteFile(File JavaDoc fileToDelete) {
216         boolean result = true;
217         if (fileToDelete != null && fileToDelete.exists()) {
218             if (fileToDelete.isDirectory()) {
219                 File JavaDoc[] files = fileToDelete.listFiles();
220                 if (files == null) {
221                     result = false;
222                 } else {
223                     for (int i = 0; i < files.length; i++) {
224                         File JavaDoc file = files[i];
225                         if (!file.getName().equals(".") && !file.getName().equals("..")) {
226                             if (file.isDirectory()) {
227                                 result &= deleteFile(file);
228                             } else {
229                                 result &= file.delete();
230                             }
231                         }
232                     }
233                 }
234             }
235             result &= fileToDelete.delete();
236         }
237         return result;
238     }
239
240     /**
241      * Zip up a directory
242      *
243      * @param directory
244      * @param zipName
245      * @throws IOException
246      */

247     public static void zipDir(String JavaDoc directory, String JavaDoc zipName) throws IOException JavaDoc {
248         // create a ZipOutputStream to zip the data to
249
ZipOutputStream JavaDoc zos = new ZipOutputStream JavaDoc(new FileOutputStream JavaDoc(zipName));
250         String JavaDoc path = "";
251         zipDir(directory, zos, path);
252         // close the stream
253
zos.close();
254     }
255
256     /**
257      * Zip up a directory path
258      * @param directory
259      * @param zos
260      * @param path
261      * @throws IOException
262      */

263     public static void zipDir(String JavaDoc directory, ZipOutputStream JavaDoc zos, String JavaDoc path) throws IOException JavaDoc {
264         File JavaDoc zipDir = new File JavaDoc(directory);
265         // get a listing of the directory content
266
String JavaDoc[] dirList = zipDir.list();
267         byte[] readBuffer = new byte[2156];
268         int bytesIn = 0;
269         // loop through dirList, and zip the files
270
for (int i = 0; i < dirList.length; i++) {
271             File JavaDoc f = new File JavaDoc(zipDir, dirList[i]);
272             if (f.isDirectory()) {
273                 String JavaDoc filePath = f.getPath();
274                 zipDir(filePath, zos, path + f.getName() + "/");
275                 continue;
276             }
277             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(f);
278             ZipEntry JavaDoc anEntry = new ZipEntry JavaDoc(path + f.getName());
279             zos.putNextEntry(anEntry);
280             while ((bytesIn = fis.read(readBuffer)) != -1) {
281                 zos.write(readBuffer, 0, bytesIn);
282             }
283             fis.close();
284         }
285     }
286 }
Popular Tags