KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > easybeans > util > files > FileUtils


1 /**
2  * EasyBeans
3  * Copyright (C) 2006 Bull S.A.S.
4  * Contact: easybeans@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: FileUtils.java 9 2006-02-19 18:53:32Z benoitf $
23  * --------------------------------------------------------------------------
24  */

25
26 package org.objectweb.easybeans.util.files;
27
28 import java.io.File JavaDoc;
29 import java.io.FileInputStream JavaDoc;
30 import java.io.FileOutputStream JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.nio.channels.FileChannel JavaDoc;
34 import java.util.Enumeration JavaDoc;
35 import java.util.jar.JarEntry JavaDoc;
36 import java.util.jar.JarFile JavaDoc;
37
38 import org.objectweb.easybeans.log.JLog;
39 import org.objectweb.easybeans.log.JLogFactory;
40
41 /**
42  * This class manages operation done many times on files, like copying them.
43  * @author Florent Benoit
44  */

45 public final class FileUtils {
46
47     /**
48      * Size of the buffer.
49      */

50     private static final int BUFFER_SIZE = 2048;
51
52     /**
53      * Logger.
54      */

55     private static JLog logger = JLogFactory.getLog(FileUtils.class);
56
57     /**
58      * Utility class, no public constructor.
59      */

60     private FileUtils() {
61
62     }
63
64     /**
65      * Unpack the source archive in a given directory and returns directory
66      * directory created.
67      * @param packedJar source JarFile to be unpacked
68      * @param dest the destination folder
69      * @throws FileUtilsException When unpack fails
70      */

71     public static void unpack(final JarFile JavaDoc packedJar, final File JavaDoc dest) throws FileUtilsException {
72
73         JarEntry JavaDoc entry = null;
74
75         // get entries of the jar file
76
Enumeration JavaDoc entries = packedJar.entries();
77         while (entries.hasMoreElements()) {
78             entry = (JarEntry JavaDoc) entries.nextElement();
79
80             // File entry
81
File JavaDoc entryFile = new File JavaDoc(dest, entry.getName());
82
83             // Create directory
84
if (entry.isDirectory()) {
85                 if (!entryFile.exists()) {
86                     // create parent directories (with mkdirs)
87
if (!entryFile.mkdirs()) {
88                         String JavaDoc err = "Can not create directory " + entryFile + ", Check the write access.";
89                         throw new FileUtilsException(err);
90                     }
91                 }
92                 continue;
93             }
94
95             // If it's a file, we must extract the file
96
// Ensure that the directory exists.
97
entryFile.getParentFile().mkdirs();
98
99             InputStream JavaDoc is = null;
100             // get the input stream
101
try {
102                 is = packedJar.getInputStream(entry);
103                 // Dump to the file
104
dump(is, entryFile);
105             } catch (IOException JavaDoc ioe) {
106                 throw new FileUtilsException("Cannot get inputstream of entry '" + entry + "' of file '" + packedJar + "'.");
107             } finally {
108                 try {
109                     is.close();
110                 } catch (IOException JavaDoc ioe) {
111                     logger.debug("Cannot close input stream", ioe);
112                 }
113             }
114
115         }
116     }
117
118     /**
119      * Write the given input stream in the given file.
120      * @param in the inputStream to copy.
121      * @param entryFile the file where the inputStream must be dumped.
122      * @throws FileUtilsException if the dump failed.
123      */

124     private static void dump(final InputStream JavaDoc in, final File JavaDoc entryFile) throws FileUtilsException {
125
126         try {
127             // File output
128
FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(entryFile);
129             int n = 0;
130             try {
131                 // buffer
132
byte[] buffer = new byte[BUFFER_SIZE];
133                 n = in.read(buffer);
134                 while (n > 0) {
135                     out.write(buffer, 0, n);
136                     n = in.read(buffer);
137                 }
138             } finally {
139                 out.close();
140             }
141         } catch (IOException JavaDoc e) {
142             String JavaDoc err = "Error while unpacking entry " + entryFile + " : ";
143             throw new FileUtilsException(err, e);
144         }
145     }
146
147     /**
148      * Copy a file.
149      * @param src source file
150      * @param dest dest file
151      * @throws FileUtilsException if the copy of the file failed
152      */

153     public static void copyFile(final String JavaDoc src, final String JavaDoc dest) throws FileUtilsException {
154         copyFile(new File JavaDoc(src), new File JavaDoc(dest));
155     }
156
157     /**
158      * Copy a file.
159      * @param src source file
160      * @param dest dest file
161      * @throws FileUtilsException if the copy of the file failed
162      */

163     public static void copyFile(final File JavaDoc src, final File JavaDoc dest) throws FileUtilsException {
164         File JavaDoc newDest = null;
165         if (dest.isDirectory()) {
166             logger.debug("Copy a file to a directory, append source filename to directory.");
167             newDest = new File JavaDoc(dest, src.getName());
168         } else {
169             newDest = dest;
170         }
171
172         FileInputStream JavaDoc fIn = null;
173         FileOutputStream JavaDoc fOut = null;
174         FileChannel JavaDoc fcIn = null;
175         FileChannel JavaDoc fcOut = null;
176         try {
177
178             // InputStream
179
fIn = new FileInputStream JavaDoc(src);
180             fOut = new FileOutputStream JavaDoc(newDest);
181
182             // nio channel
183
FileChannel JavaDoc sourceFC = fIn.getChannel();
184             FileChannel JavaDoc targetFC = fOut.getChannel();
185
186             targetFC.transferFrom(sourceFC, 0, sourceFC.size());
187         } catch (Exception JavaDoc e) {
188             throw new FileUtilsException("Error during copy file : " + src + " -> " + dest, e);
189         } finally {
190             try {
191                 fOut.close();
192                 fIn.close();
193                 fcOut.close();
194                 fcIn.close();
195             } catch (Exception JavaDoc e) {
196                 logger.debug("Cannot close some i/o which are open.", e);
197             }
198
199         }
200     }
201
202     /**
203      * @param path file/directory to be deleted
204      * @return true if deletion was OK
205      */

206     public static boolean delete(final String JavaDoc path) {
207         return delete(new File JavaDoc(path));
208     }
209
210     /**
211      * @param f file/directory to be deleted
212      * @return true if deletion was OK
213      */

214     public static boolean delete(final File JavaDoc f) {
215         if (f.isFile()) {
216             return f.delete();
217         }
218         // else (if directory)
219
File JavaDoc[] children = f.listFiles();
220         if (children == null) {
221             // no children
222
return f.delete();
223         }
224
225         // There are children
226
boolean result = true;
227         for (int i = 0; i < children.length; i++) {
228             result &= delete(children[i]);
229         }
230         return result && f.delete();
231     }
232
233     /**
234      * Copy a directory recursively.
235      * @param src source directory
236      * @param dest dest directory
237      * @throws FileUtilsException if the copy of the directory failed
238      */

239     public static void copyDirectory(final String JavaDoc src, final String JavaDoc dest) throws FileUtilsException {
240         copyDirectory(new File JavaDoc(src), new File JavaDoc(dest));
241     }
242
243     /**
244      * Copy a directory recursively.
245      * @param src source directory
246      * @param dest dest directory
247      * @throws FileUtilsException if the copy of the directory failed
248      */

249     public static void copyDirectory(final File JavaDoc src, final File JavaDoc dest) throws FileUtilsException {
250
251         if (!src.isDirectory()) {
252             // We don not accept file arguments !
253
throw new IllegalArgumentException JavaDoc("Source '" + src + "' must be a directory");
254         }
255
256         // create the destination directory if it is inexistant
257
if (!dest.exists()) {
258             dest.mkdirs();
259         }
260
261         // copy the files of the source directory
262
File JavaDoc[] childs = src.listFiles();
263         if (childs != null) {
264             // childs
265
for (int i = 0; i < childs.length; i++) {
266                 File JavaDoc child = childs[i];
267                 if (child.isFile()) {
268                     // file
269
copyFile(child, dest);
270                 } else {
271                     // directory
272
copyDirectory(child, new File JavaDoc(dest, child.getName()));
273                 }
274             }
275         }
276     }
277
278 }
279
Popular Tags