KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > caramel > util > FileUtils


1 /*
2 ** Caramel - Non-GUI Java Addons
3 ** Copyright (c) 2001, 2002, 2003 by Gerald Bauer
4 **
5 ** This program is free software.
6 **
7 ** You may redistribute it and/or modify it under the terms of the GNU
8 ** Lesser General Public License as published by the Free Software Foundation.
9 ** Version 2.1 of the license should be included with this distribution in
10 ** the file LICENSE, as well as License.html. If the license is not
11 ** included with this distribution, you may find a copy at the FSF web
12 ** site at 'www.gnu.org' or 'www.fsf.org', or you may write to the
13 ** Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
14 **
15 ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
16 ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
17 ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
18 ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
19 ** REDISTRIBUTION OF THIS SOFTWARE.
20 **
21 */

22
23 package caramel.util;
24
25 import java.io.*;
26 import java.net.*;
27 import java.util.*;
28 import houston.*;
29
30 public class FileUtils
31 {
32    static Logger T = Logger.getLogger( FileUtils.class );
33
34    /**
35     * Strips path and extension from a filename example: lib/venus.jnlp ->
36     * venus
37     */

38    public static String JavaDoc getBaseName( String JavaDoc name )
39    {
40       // 1) Strip path.
41
String JavaDoc base = new File( name ).getName();
42       // 2) Strip possible extension.
43
int index = base.lastIndexOf( '.' );
44       if( index != -1 )
45          base = base.substring( 0, index );
46
47       return base;
48    }
49
50    public static String JavaDoc getFileAsString( String JavaDoc name ) throws IOException
51    {
52       File file = new File( name );
53
54       return getFileAsString( file );
55    }
56
57    public static String JavaDoc getFileAsString( File file ) throws IOException
58    {
59       StringBuffer JavaDoc text = new StringBuffer JavaDoc();
60
61       FileReader in = new FileReader( file );
62       char buffer[] = new char[4096];
63       int bytes_read;
64       while( ( bytes_read = in.read( buffer ) ) != -1 )
65          text.append( new String JavaDoc( buffer, 0, bytes_read ) );
66
67       return text.toString();
68    }
69
70    public static String JavaDoc getFileExtension( String JavaDoc filename )
71    {
72       // returns extension including .
73

74       // Now strip of possible extension.
75

76       String JavaDoc extension = "";
77       int index = filename.lastIndexOf( '.' );
78       if( index != -1 )
79          extension = filename.substring( index );
80
81       return extension;
82    }
83
84    public static String JavaDoc getFileExtension( File file )
85    {
86       // returns extension including .
87

88       // Strip of path first.
89
String JavaDoc base = file.getName();
90       // Now strip of possible extension.
91

92       String JavaDoc extension = "";
93       int index = base.lastIndexOf( '.' );
94       if( index != -1 )
95          extension = base.substring( index );
96
97       return extension;
98    }
99
100    public static String JavaDoc getFileExtension( String JavaDoc filename, boolean keepDot )
101    {
102       filename = filename.replace( '\\', '/' );
103
104       String JavaDoc name;
105       int namePos = filename.lastIndexOf( '/' );
106       if( namePos != -1 )
107       {
108          name = filename.substring( namePos + 1 );
109       }
110       else
111       {
112          // no path info found
113

114          name = filename;
115       }
116
117       String JavaDoc ext;
118       int extPos = name.lastIndexOf( '.' );
119       if( extPos != -1 )
120       {
121          if( keepDot )
122             ext = name.substring( extPos );
123          else
124             ext = name.substring( extPos + 1 );
125       }
126       else
127       {
128          // no extension found
129

130          ext = "";
131       }
132
133       return ext;
134    }
135
136    public static String JavaDoc getFileExtension( File file, boolean keepDot )
137    {
138       // Strip path first.
139
String JavaDoc base = file.getName();
140
141       String JavaDoc extension = "";
142       int index = base.lastIndexOf( '.' );
143       if( index != -1 )
144       {
145          if( keepDot )
146             extension = base.substring( index );
147          else
148             extension = base.substring( index + 1 );
149       }
150       return extension;
151    }
152
153    public static String JavaDoc getInputStreamAsString( InputStream inStream ) throws IOException
154    {
155       // todo: should i wrap inputStream in BufferedInputStream?
156

157       StringBuffer JavaDoc text = new StringBuffer JavaDoc();
158
159       InputStreamReader in = new InputStreamReader( inStream );
160       char buffer[] = new char[4096];
161       int bytes_read;
162       while( ( bytes_read = in.read( buffer ) ) != -1 )
163          text.append( new String JavaDoc( buffer, 0, bytes_read ) );
164
165       return text.toString();
166    }
167
168    public static File getRoot( File file )
169    {
170       File parent = file;
171       while( parent.getParentFile() != null )
172          parent = parent.getParentFile();
173
174       return parent;
175       // return file without parent (aka root)
176
}
177
178    public static void copy( File from_file, File to_file ) throws IOException
179    {
180       // First make sure the source file exists, is a file, and is readable.
181
if( !from_file.exists() )
182          abort( "FileCopy: no such source file: " + from_file.getName() );
183
184       if( !from_file.isFile() )
185          abort( "FileCopy: can't copy directory: " + from_file.getName() );
186
187       if( !from_file.canRead() )
188          abort( "FileCopy: source file is unreadable: " + from_file.getName() );
189
190       // If the destination is a directory, use the source file name
191
// as the destination file name
192
if( to_file.isDirectory() )
193          to_file = new File( to_file, from_file.getName() );
194
195       // If the destination exists, make sure it is a writeable file
196
// and ask before overwriting it. If the destination doesn't
197
// exist, make sure the directory exists and is writeable.
198
if( to_file.exists() )
199       {
200          if( !to_file.canWrite() )
201             abort( "FileCopy: destination file is unwriteable: " + to_file.getName() );
202       }
203       else
204       {
205          // if file doesn't exist, check if directory exists and is writeable.
206
// If getParent() returns null, then the directory is the current dir.
207
// so look up the user.dir system property to find out what that is.
208
String JavaDoc parent = to_file.getParent();
209          // Get the destination directory
210
if( parent == null )
211             parent = System.getProperty( "user.dir" );
212
213          // or CWD
214
File dir = new File( parent );
215          // Convert it to a file.
216
if( !dir.exists() )
217             abort( "FileCopy: destination directory doesn't exist: " + parent );
218
219          if( dir.isFile() )
220             abort( "FileCopy: destination is not a directory: " + parent );
221
222          if( !dir.canWrite() )
223             abort( "FileCopy: destination directory is unwriteable: " + parent );
224
225       }
226
227       // If we've gotten this far, then everything is okay.
228
// So we copy the file, a buffer of bytes at a time.
229
FileInputStream from = null;
230       // Stream to read from source
231
FileOutputStream to = null;
232       // Stream to write to destination
233
try
234       {
235          from = new FileInputStream( from_file );
236          // Create input stream
237
to = new FileOutputStream( to_file );
238          // Create output stream
239
byte[] buffer = new byte[4096];
240          // A buffer to hold file contents
241
int bytes_read;
242          // How many bytes in buffer
243
// Read a chunk of bytes into the buffer, then write them out,
244
// looping until we reach the end of the file (when read() returns -1).
245
// Note the combination of assignment and comparison in this while
246
// loop. This is a common I/O programming idiom.
247
while( ( bytes_read = from.read( buffer ) ) != -1 )
248          {
249             // Read bytes until EOF
250
to.write( buffer, 0, bytes_read );
251          }
252          // write bytes
253
}
254       // Always close the streams, even if exceptions were thrown
255
finally
256       {
257          if( from != null )
258          {
259             try
260             {
261                from.close();
262             }
263             catch( IOException e )
264             {
265                ;
266             }
267          }
268          if( to != null )
269          {
270             try
271             {
272                to.close();
273             }
274             catch( IOException e )
275             {
276                ;
277             }
278          }
279       }
280    }
281
282    /**
283     * The static method that actually performs the file copy. Before copying
284     * the file, however, it performs a lot of tests to make sure everything is
285     * as it should be.
286     */

287    public static void copy( String JavaDoc from_name, String JavaDoc to_name ) throws IOException
288    {
289       File from_file = new File( from_name );
290       // Get File objects from Strings
291
File to_file = new File( to_name );
292
293       // First make sure the source file exists, is a file, and is readable.
294
if( !from_file.exists() )
295          abort( "FileCopy: no such source file: " + from_name );
296
297       if( !from_file.isFile() )
298          abort( "FileCopy: can't copy directory: " + from_name );
299
300       if( !from_file.canRead() )
301          abort( "FileCopy: source file is unreadable: " + from_name );
302
303       // If the destination is a directory, use the source file name
304
// as the destination file name
305
if( to_file.isDirectory() )
306          to_file = new File( to_file, from_file.getName() );
307
308       // If the destination exists, make sure it is a writeable file
309
// and ask before overwriting it. If the destination doesn't
310
// exist, make sure the directory exists and is writeable.
311
if( to_file.exists() )
312       {
313          if( !to_file.canWrite() )
314             abort( "FileCopy: destination file is unwriteable: " + to_name );
315
316       }
317       else
318       {
319          // if file doesn't exist, check if directory exists and is writeable.
320
// If getParent() returns null, then the directory is the current dir.
321
// so look up the user.dir system property to find out what that is.
322
String JavaDoc parent = to_file.getParent();
323          // Get the destination directory
324
if( parent == null )
325             parent = System.getProperty( "user.dir" );
326
327          // or CWD
328
File dir = new File( parent );
329          // Convert it to a file.
330
if( !dir.exists() )
331             abort( "FileCopy: destination directory doesn't exist: " + parent );
332
333          if( dir.isFile() )
334             abort( "FileCopy: destination is not a directory: " + parent );
335
336          if( !dir.canWrite() )
337             abort( "FileCopy: destination directory is unwriteable: " + parent );
338
339       }
340
341       // If we've gotten this far, then everything is okay.
342
// So we copy the file, a buffer of bytes at a time.
343
FileInputStream from = null;
344       // Stream to read from source
345
FileOutputStream to = null;
346       // Stream to write to destination
347
try
348       {
349          from = new FileInputStream( from_file );
350          // Create input stream
351
to = new FileOutputStream( to_file );
352          // Create output stream
353
byte[] buffer = new byte[4096];
354          // A buffer to hold file contents
355
int bytes_read;
356          // How many bytes in buffer
357
// Read a chunk of bytes into the buffer, then write them out,
358
// looping until we reach the end of the file (when read() returns -1).
359
// Note the combination of assignment and comparison in this while
360
// loop. This is a common I/O programming idiom.
361
while( ( bytes_read = from.read( buffer ) ) != -1 )
362          {
363             // Read bytes until EOF
364
to.write( buffer, 0, bytes_read );
365          }
366          // write bytes
367
}
368       // Always close the streams, even if exceptions were thrown
369
finally
370       {
371          if( from != null )
372          {
373             try
374             {
375                from.close();
376             }
377             catch( IOException e )
378             {
379                ;
380             }
381          }
382          if( to != null )
383          {
384             try
385             {
386                to.close();
387             }
388             catch( IOException e )
389             {
390                ;
391             }
392          }
393       }
394    }
395
396    public static void download( DownloadTracker tracker, URL from, File toFile )
397           throws IOException
398    {
399       tracker.info( "connecting..." );
400       URLConnection con = from.openConnection();
401       con.connect();
402       tracker.info( "connection established" );
403
404       long size = con.getContentLength();
405       T.debug( "content length=" + size );
406
407       tracker.start( size );
408       tracker.info( "downloading " + size + " bytes..." );
409
410       InputStream in = con.getInputStream();
411       // Open stream;
412

413       // Make sure path exists
414
toFile.getParentFile().mkdirs();
415
416       FileOutputStream fout = new FileOutputStream( toFile );
417       OutputStream out = new BufferedOutputStream( fout );
418
419       try
420       {
421          byte buffer[] = new byte[4096];
422          int bytes_read = 0;
423          int total_bytes_read = 0;
424
425          while( ( bytes_read = in.read( buffer ) ) != -1 )
426          {
427             out.write( buffer, 0, bytes_read );
428
429             total_bytes_read += bytes_read;
430             tracker.update( total_bytes_read );
431          }
432
433          out.flush();
434       }
435       finally
436       {
437          try
438          {
439             out.close();
440          }
441          catch( IOException e )
442          {}
443          try
444          {
445             in.close();
446          }
447          catch( IOException e )
448          {}
449          tracker.stop();
450       }
451    }
452
453    public static File[] findByExt( File base, String JavaDoc ext )
454    {
455       // searches recursively in base directory
456
// for files that match the extension ext
457

458       Vector result = new Vector();
459
460       findByExtWorker( result, base, ext );
461
462       // make generic array into a type-safe array
463
Object JavaDoc objs[] = result.toArray();
464       File files[] = new File[objs.length];
465       System.arraycopy( objs, 0, files, 0, objs.length );
466
467       return files;
468    }
469
470    public static String JavaDoc prettyPrintFileSize( File file )
471    {
472       long size = file.length();
473
474       // use kilobytes (1028 bytes) for now
475
if( size < 1028 )
476          return "1 k";
477
478       size = size / 1028;
479
480       return size + " k";
481    }
482
483    public static void saveStreamToFile( InputStream in, File outFile )
484           throws IOException
485    {
486       FileOutputStream out = null;
487       try
488       {
489          out = new FileOutputStream( outFile );
490          byte[] buf = new byte[4096];
491          int bytes_read;
492          while( ( bytes_read = in.read( buf ) ) != -1 )
493             out.write( buf, 0, bytes_read );
494       }
495       finally
496       {
497          if( in != null )
498             try
499             {
500                in.close();
501             }
502             catch( IOException e )
503             {}
504
505          if( out != null )
506             try
507             {
508                out.close();
509             }
510             catch( IOException e )
511             {}
512       }
513    }
514
515
516    /**
517     * A convenience method to throw an exception
518     */

519    private static void abort( String JavaDoc msg ) throws IOException
520    {
521       throw new IOException( msg );
522    }
523
524    private static void findByExtWorker( Vector result, File base, String JavaDoc ext )
525    {
526       File files[] = base.listFiles();
527
528       for( int i = 0; i < files.length; i++ )
529       {
530          File file = files[i];
531          if( !file.isDirectory() )
532          {
533             String JavaDoc currentExt = getFileExtension( file );
534             if( currentExt.equalsIgnoreCase( ext ) )
535             {
536                // bingo; add to result set
537

538                T.debug( "[find] match -> " + file.getAbsolutePath() );
539                result.add( file );
540             }
541          }
542          else
543          {
544             // file is a directory, recurse
545

546             findByExtWorker( result, file, ext );
547          }
548       }
549    }
550
551 }
552 // end of class
553
Popular Tags