KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > gnat > util > FileUtil


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

16
17 //This handy class ripped from Avalaon util.io package.
18
//package org.apache.avalon.util.io;
19
package org.apache.taglibs.gnat.util;
20
21 import java.io.*;
22 import java.net.URL JavaDoc;
23
24 /**
25  * This class provides basic facilities for manipulating files.
26  *
27  * @author <a HREF="mailto:donaldp@apache.org">Peter Donald</a>
28  */

29 public final class FileUtil
30 {
31     /**
32      * Private constructor to prevent instantiation.
33      *
34      */

35     private FileUtil()
36     {
37     }
38
39     public static String JavaDoc removeExtention( final String JavaDoc filename )
40     {
41         final int index = filename.lastIndexOf( '.' );
42         
43         if( -1 == index )
44         {
45             return filename;
46         }
47         else
48         {
49             return filename.substring( 0, index );
50         }
51     }
52
53     public static String JavaDoc removePath( final String JavaDoc filepath )
54     {
55         final int index = filepath.lastIndexOf( File.separator );
56
57         if( -1 == index )
58         {
59             return filepath;
60         }
61         else
62         {
63             return filepath.substring( index + 1 );
64         }
65     }
66
67     /**
68      * Copy file from source to destination.
69      */

70     public static void copyFileToDirectory( final String JavaDoc source,
71                                             final String JavaDoc destinationDirectory )
72         throws IOException
73     {
74         copyFileToDirectory( new File( source ), new File( destinationDirectory ) );
75     }
76
77     /**
78      * Copy file from source to destination.
79      */

80     public static void copyFileToDirectory( final File source,
81                                             final File destinationDirectory )
82         throws IOException
83     {
84         if( destinationDirectory.exists() && !destinationDirectory.isDirectory() )
85         {
86             throw new IllegalArgumentException JavaDoc( "Destination is not a directory" );
87         }
88
89         copyFile( source, new File( destinationDirectory, source.getName() ) );
90     }
91
92     /**
93      * Copy file from source to destination.
94      */

95     public static void copyFile( final File source, final File destination )
96         throws IOException
97     {
98         //check source exists
99
if( !source.exists() )
100         {
101             throw new IOException( "File " + source + " does not exist" );
102         }
103
104         //does destinations directory exist ?
105
if( !destination.getParentFile().exists() )
106         {
107             destination.mkdirs();
108         }
109
110         //make sure we can write to destination
111
if( destination.exists() && !destination.canWrite() )
112         {
113             throw new IOException( "Unable to open file " + destination + " for writing." );
114         }
115
116         copy( new FileInputStream( source ), new FileOutputStream( destination ) );
117
118         if( source.length() != destination.length() )
119         {
120             throw new IOException( "Failed to copy full contents from " + source +
121                                    " to " + destination );
122         }
123     }
124
125     public static void copyURLToFile( final URL JavaDoc source, final File destination )
126         throws IOException
127     {
128         //does destinations directory exist ?
129
if( !destination.getParentFile().exists() )
130         {
131             destination.mkdirs();
132         }
133         
134         //make sure we can write to destination
135
if( destination.exists() && !destination.canWrite() )
136         {
137             throw new IOException( "Unable to open file " + destination + " for writing." );
138         }
139         
140         copy( source.openStream(), new FileOutputStream( destination ) );
141     }
142
143     /**
144      * Copy stream-data from source to destination.
145      */

146     public static void copy( final InputStream source, final OutputStream destination )
147         throws IOException
148     {
149         try
150         {
151             final BufferedInputStream input = new BufferedInputStream( source );
152             final BufferedOutputStream output = new BufferedOutputStream( destination );
153             
154             final int BUFFER_SIZE = 1024 * 4;
155             final byte[] buffer = new byte[ BUFFER_SIZE ];
156             
157             while( true )
158             {
159                 final int count = input.read( buffer, 0, BUFFER_SIZE );
160                 if( -1 == count ) break;
161                 
162                 // write out those same bytes
163
output.write( buffer, 0, count );
164             }
165             
166             //needed to flush cache
167
input.close();
168             output.close();
169         }
170         finally
171         {
172             try { source.close(); } catch( final IOException ioe ) {}
173             try { destination.close(); } catch( final IOException ioe ) {}
174         }
175     }
176
177     /** Will concatenate 2 paths, dealing with ..
178      * ( /a/b/c + d = /a/b/d, /a/b/c + ../d = /a/d )
179      *
180      * Thieved from Tomcat sources...
181      *
182      * @return null if error occurs
183      */

184     public static String JavaDoc catPath( String JavaDoc lookupPath, String JavaDoc path )
185     {
186         // Cut off the last slash and everything beyond
187
int index = lookupPath.lastIndexOf( "/" );
188         lookupPath = lookupPath.substring( 0, index );
189         
190         // Deal with .. by chopping dirs off the lookup path
191
while( path.startsWith( "../" ) )
192         {
193             if( lookupPath.length() > 0 )
194             {
195                 index = lookupPath.lastIndexOf( "/" );
196                 lookupPath = lookupPath.substring( 0, index );
197             }
198             else
199             {
200                 // More ..'s than dirs, return null
201
return null;
202             }
203             
204             index = path.indexOf( "../" ) + 3;
205             path = path.substring( index );
206         }
207         
208         return lookupPath + "/" + path;
209     }
210
211     public static File resolveFile( final File baseFile, String JavaDoc filename )
212     {
213         if( '/' != File.separatorChar )
214         {
215             filename = filename.replace( '/', File.separatorChar );
216         }
217
218         if( '\\' != File.separatorChar )
219         {
220             filename = filename.replace( '\\', File.separatorChar );
221         }
222
223         // deal with absolute files
224
if( filename.startsWith( File.separator ) )
225         {
226             File file = new File( filename );
227
228             try { file = file.getCanonicalFile(); }
229             catch( final IOException ioe ) {}
230
231             return file;
232         }
233
234         final char[] chars = filename.toCharArray();
235         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
236
237         //remove duplicate file seperators in succession - except
238
//on win32 as UNC filenames can be \\AComputer\AShare\myfile.txt
239
int start = 0;
240         if( '\\' == File.separatorChar )
241         {
242             sb.append( filename.charAt( 0 ) );
243             start++;
244         }
245
246         for( int i = start; i < chars.length; i++ )
247         {
248             final boolean doubleSeparator =
249                 File.separatorChar == chars[ i ] && File.separatorChar == chars[ i - 1 ];
250
251             if( !doubleSeparator ) sb.append( chars[ i ] );
252         }
253         
254         filename = sb.toString();
255
256         //must be relative...
257
File file = (new File( baseFile, filename )).getAbsoluteFile();
258
259         try { file = file.getCanonicalFile(); }
260         catch( final IOException ioe ) {}
261
262         return file;
263     }
264
265     /**
266      * Delete a file. If file is directory delete it and all sub-directories.
267      */

268     public static void forceDelete( final String JavaDoc file )
269         throws IOException
270     {
271         forceDelete( new File( file ) );
272     }
273
274     /**
275      * Delete a file. If file is directory delete it and all sub-directories.
276      */

277     public static void forceDelete( final File file )
278         throws IOException
279     {
280         if( file.isDirectory() ) deleteDirectory( file );
281         else
282         {
283             if( false == file.delete() )
284             {
285                 throw new IOException( "File " + file + " unable to be deleted." );
286             }
287         }
288     }
289
290     /**
291      * Recursively delete a directory.
292      */

293     public static void deleteDirectory( final String JavaDoc directory )
294         throws IOException
295     {
296         deleteDirectory( new File( directory ) );
297     }
298
299     /**
300      * Recursively delete a directory.
301      */

302     public static void deleteDirectory( final File directory )
303         throws IOException
304     {
305         if( !directory.exists() ) return;
306
307         cleanDirectory( directory );
308         if( false == directory.delete() )
309         {
310             throw new IOException( "Directory " + directory + " unable to be deleted." );
311         }
312     }
313
314     /**
315      * Clean a directory without deleting it.
316      */

317     public static void cleanDirectory( final String JavaDoc directory )
318         throws IOException
319     {
320         cleanDirectory( new File( directory ) );
321     }
322     
323     /**
324      * Clean a directory without deleting it.
325      */

326     public static void cleanDirectory( final File directory )
327         throws IOException
328     {
329         if( !directory.exists() )
330         {
331             throw new IllegalArgumentException JavaDoc( directory + " does not exist" );
332         }
333         
334         if( !directory.isDirectory() )
335         {
336             throw new IllegalArgumentException JavaDoc( directory + " is not a directory" );
337         }
338         
339         final File[] files = directory.listFiles();
340         
341         for( int i = 0; i < files.length; i++ )
342         {
343             final File file = files[ i ];
344             
345             if( file.isFile() ) file.delete();
346             else if( file.isDirectory() )
347             {
348                 cleanDirectory( file );
349                 if( false == file.delete() )
350                 {
351                     throw new IOException( "Directory " + file + " unable to be deleted." );
352                 }
353             }
354         }
355     }
356 }
357
Popular Tags