KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > util > FileUtils


1 /*
2  Copyright (c) 2003 eInnovation Inc. All rights reserved
3
4  This library is free software; you can redistribute it and/or modify it under the terms
5  of the GNU Lesser General Public License as published by the Free Software Foundation;
6  either version 2.1 of the License, or (at your option) any later version.
7
8  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10  See the GNU Lesser General Public License for more details.
11  */

12
13 package com.openedit.util;
14
15 import java.io.File JavaDoc;
16 import java.io.FileOutputStream JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.InputStream JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.io.Reader JavaDoc;
21 import java.io.Writer JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 /**
29  * Some file utility methods such as recursive delete.
30  */

31 public class FileUtils
32 {
33     OutputFiller fieldFiller = new OutputFiller();
34     private static final Log log = LogFactory.getLog(FileUtils.class);
35     /**
36      * Create a temporary directory with a unique name beginning with the given
37      * prefix.
38      *
39      * @param inPrefix
40      * The prefix for the created directory
41      *
42      * @return DOCME
43      *
44      * @throws IOException
45      * DOCME
46      */

47     public File JavaDoc createTempDir( String JavaDoc inPrefix ) throws IOException JavaDoc
48     {
49         File JavaDoc tempDir = File.createTempFile( inPrefix, null );
50         tempDir.delete();
51         tempDir.mkdir();
52
53         return tempDir;
54     }
55
56     /**
57      * DOCME
58      *
59      * @param fname
60      * DOCME
61      */

62     public void deleteAll( String JavaDoc fname )
63     {
64         File JavaDoc f = new File JavaDoc( fname );
65         deleteAll( f );
66     }
67
68     /**
69      * Deletes any files in this directory that match the wildcard
70      * @param inMatch
71      */

72     public void deleteMatch( String JavaDoc inMatch )
73     {
74         //get the parent, list the children, find the match, delete
75
File JavaDoc search = new File JavaDoc( inMatch );
76         File JavaDoc dir = search.getParentFile();
77
78         File JavaDoc[] all = dir.listFiles();
79         if ( all != null)
80         {
81             for (int i = 0; i < all.length; i++)
82             {
83                 File JavaDoc f = all[i];
84                 if ( PathUtilities.match(f.getName(), search.getName() ) )
85                 {
86                     log.info("deleted " + f.getName());
87                     f.delete(); //should this do dirs?
88
}
89             }
90         }
91     }
92     
93     public boolean deleteOlderVersions( String JavaDoc inDir )
94     {
95         System.gc();
96         boolean requiresRestart = false;
97         Map JavaDoc map = new HashMap JavaDoc();
98         //get the parent, list the children, find the match, delete
99
File JavaDoc dir = new File JavaDoc( inDir );
100
101         File JavaDoc[] all = dir.listFiles();
102         if ( all != null)
103         {
104             for (int i = 0; i < all.length; i++)
105             {
106                 File JavaDoc f = all[i];
107                 String JavaDoc fileName = f.getName();
108                 int dashIndex = fileName.lastIndexOf('-');
109                 if (dashIndex >= 0)
110                 {
111                     String JavaDoc base = fileName.substring(0, dashIndex);
112                     String JavaDoc version = fileName.substring(dashIndex + 1 );
113                     String JavaDoc highestVersion = (String JavaDoc)map.get(base);
114                     if (highestVersion == null || highestVersion.compareTo(version) < 0)
115                     {
116                         map.put(base, version);
117                     }
118                 }
119             }
120
121             for (int i = 0; i < all.length; i++)
122             {
123                 File JavaDoc f = all[i];
124                 String JavaDoc fileName = f.getName();
125                 int dashIndex = fileName.lastIndexOf('-');
126                 if (dashIndex >= 0)
127                 {
128                     String JavaDoc base = fileName.substring(0, dashIndex);
129                     String JavaDoc version = fileName.substring(dashIndex + 1);
130                     String JavaDoc highestVersion = (String JavaDoc)map.get(base);
131                     if (!version.equals(highestVersion))
132                     {
133                         if (f.delete())
134                         {
135                             log.info("deleting " + f.getName());
136                         }
137                         else
138                         {
139                             log.info("deleting " + f.getName() + " on exit");
140                             f.deleteOnExit();
141                             requiresRestart = true;
142                         }
143                     }
144                 }
145             }
146         }
147         return requiresRestart;
148     }
149     
150     public void deleteAll( File JavaDoc file )
151     {
152         if (file.isDirectory())
153         {
154             // If it's a dir, then delete everything in it.
155
File JavaDoc[] fileList = file.listFiles();
156
157             if (fileList != null)
158             {
159                 for ( int idx = 0; idx < fileList.length; idx++ )
160                     deleteAll( fileList[idx] );
161             }
162         }
163
164         // Now delete ourselves, whether a file or a dir.
165
file.delete();
166     }
167     public void copyFileByMatch( String JavaDoc inMatch, String JavaDoc outDir) throws IOException JavaDoc
168     {
169         File JavaDoc out = new File JavaDoc( outDir );
170         out.mkdirs();
171         copyFileByMatch(inMatch, out );
172     }
173     public void copyFileByMatch( String JavaDoc inMatch, File JavaDoc outDir) throws IOException JavaDoc
174     {
175         File JavaDoc file = new File JavaDoc( inMatch );
176         File JavaDoc dir = file.getParentFile();
177
178         File JavaDoc[] all = dir.listFiles();
179         if ( all != null)
180         {
181             for (int i = 0; i < all.length; i++)
182             {
183                 File JavaDoc f = all[i];
184                 if ( PathUtilities.match(f.getName(), file.getName() ) )
185                 {
186                     copyFiles(f, outDir);
187                 }
188             }
189         }
190     }
191
192     /**
193      * DOCME
194      *
195      * @param inSource
196      * DOCME
197      * @param inDest
198      * DOCME
199      * @param inBuffer
200      * DOCME
201      *
202      * @throws IOException
203      * DOCME
204      */

205     public void dirCopy( File JavaDoc inSource, File JavaDoc inDest ) throws IOException JavaDoc
206     {
207         if (inSource.isDirectory())
208         {
209             inDest.mkdirs();
210
211             File JavaDoc[] files = inSource.listFiles();
212             if( files != null)
213             {
214                 for ( int i = 0; i < files.length; i++ )
215                 {
216                     // The child directory
217
File JavaDoc newDest = new File JavaDoc( inDest, files[i].getName() );
218     
219                     if (files[i].isDirectory())
220                     {
221                         dirCopy( files[i], newDest );
222                     }
223                     else
224                     {
225                         fileCopy( files[i], newDest );
226                     }
227                 }
228             }
229         }
230     }
231     /**
232      * Does a move even if the directory already exist
233      * Also creates a directory for file to be moved into
234      * @param inSource
235      * @param inDest
236      * @throws IOException
237      */

238     public void move( File JavaDoc inSource, File JavaDoc inDest ) throws IOException JavaDoc
239     {
240         if (inSource.isDirectory())
241         {
242             inDest.mkdirs();
243
244             File JavaDoc[] files = inSource.listFiles();
245             if( files != null)
246             {
247                 for ( int i = 0; i < files.length; i++ )
248                 {
249                     // The child directory
250
File JavaDoc newDest = new File JavaDoc( inDest, files[i].getName() );
251     
252                     if (files[i].isDirectory())
253                     {
254                         move( files[i], newDest );
255                     }
256                     else
257                     {
258                         files[i].renameTo( newDest );
259                     }
260                 }
261             }
262             inSource.delete();
263         }
264         else
265         {
266             inDest.getParentFile().mkdirs();
267             inSource.renameTo( inDest );
268         }
269     }
270
271     /**
272      * DOCME
273      *
274      * @param src
275      * DOCME
276      * @param dst
277      * DOCME
278      * @param buffer
279      * DOCME
280      *
281      * @throws IOException
282      * DOCME
283      */

284     public void fileCopy( File JavaDoc src, File JavaDoc dst ) throws IOException JavaDoc
285     {
286         fieldFiller.fill(src,dst);
287
288         // Preserve the modification date of the original file.
289
dst.setLastModified( src.lastModified() );
290     }
291     public void copyFiles( String JavaDoc source, String JavaDoc destination ) throws IOException JavaDoc
292     {
293         copyFiles( new File JavaDoc( source ), new File JavaDoc( destination ) );
294     }
295     public void copyFiles( File JavaDoc source, File JavaDoc destination ) throws IOException JavaDoc
296     {
297         if (source.isDirectory())
298         {
299             if( destination.exists() && !destination.isDirectory() )
300             {
301                 destination.delete();
302             }
303             destination.mkdirs();
304
305             //loop over all the sub files
306
File JavaDoc[] children = source.listFiles();
307
308             for ( int i = 0; i < children.length; i++ )
309             {
310                 copyFiles( children[i], new File JavaDoc( destination, children[i].getName() ) );
311             }
312         }
313         else
314         {
315             if( destination.isDirectory() )
316             {
317                 copyFiles( source,new File JavaDoc( destination , source.getName() ) );
318             }
319             else
320             {
321                 destination.getParentFile().mkdirs();
322                 fieldFiller.fill( source,destination );
323                 destination.setLastModified(source.lastModified());
324             }
325         }
326     }
327     /**
328      * This closes the input stream
329      * @param inInput
330      * @param inOutputFile
331      * @throws IOException
332      */

333     public void writeFile( InputStream JavaDoc inInput, File JavaDoc inOutputFile ) throws IOException JavaDoc
334     {
335         //TODO: Could probably start using java.nio classes
336
// Write the content
337

338 // Create any parent directories, if necessary.
339
inOutputFile.getParentFile().mkdirs();
340         OutputStream JavaDoc out = new FileOutputStream JavaDoc( inOutputFile );
341         try
342         {
343             fieldFiller.fill( inInput, out );
344             out.flush();
345         }
346         finally
347         {
348             if ( inInput != null)
349             {
350                 inInput.close();
351             }
352             out.close();
353         }
354     }
355
356     /**
357      * @param inIn
358      */

359     public static void safeClose(Reader JavaDoc inIn)
360     {
361         if ( inIn != null)
362         {
363             try
364             {
365                 inIn.close();
366             }
367             catch (IOException JavaDoc ex)
368             {
369                 log.error(ex);
370             }
371         }
372     }
373     public static void safeClose(InputStream JavaDoc inIn)
374     {
375         if ( inIn != null)
376         {
377             try
378             {
379                 inIn.close();
380             }
381             catch (IOException JavaDoc ex)
382             {
383                 log.error(ex);
384             }
385         }
386     }
387     public static void safeClose(OutputStream JavaDoc inIn)
388     {
389         if ( inIn != null)
390         {
391             try
392             {
393                 inIn.close();
394             }
395             catch (IOException JavaDoc ex)
396             {
397                 log.error(ex);
398             }
399         }
400     }
401     public static void safeClose(Writer JavaDoc inIn)
402     {
403         if ( inIn != null)
404         {
405             try
406             {
407                 inIn.close();
408             }
409             catch (IOException JavaDoc ex)
410             {
411                 log.error(ex);
412             }
413         }
414     }
415 }
Popular Tags