KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > FileUtil


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.util;
24
25 import java.io.*;
26 import java.io.IOException JavaDoc;
27 import java.io.FilenameFilter JavaDoc;
28 import java.util.*;
29 import java.net.URL JavaDoc;
30 import java.net.MalformedURLException JavaDoc;
31 import java.nio.channels.*;
32 import java.util.jar.*;
33 import java.util.zip.ZipEntry JavaDoc;
34 import com.sun.logging.LogDomains;
35
36 //START OF IASRI 4660742
37
import java.util.logging.*;
38 import com.sun.logging.*;
39 //END OF IASRI 4660742
40

41 /**
42  * File pathname/location management utility methods
43  */

44 public class FileUtil {
45
46     // START OF IASRI 4660742
47
static Logger _logger=LogDomains.getLogger(LogDomains.UTIL_LOGGER);
48     // END OF IASRI 4660742
49

50     // START OF IASRI 4679641
51
// private static final boolean debug = false;
52
private static final boolean debug = com.sun.enterprise.util.logging.Debug.enabled;
53     // END OF IASRI 4679641
54
private static final String JavaDoc JAR_FILE_NAME = "j2ee.jar";
55     private static final String JavaDoc HOME_DIR_PROP="com.sun.enterprise.home";
56     private static final String JavaDoc DEFAULT_HOME_DIR=System.getProperty("user.dir");
57
58     // Platform-independent separator character used in jar file entries
59
public static final char JAR_SEPARATOR_CHAR = '/';
60
61     private static final long JAR_ENTRY_UNKNOWN_VALUE = -1;
62     private static final int BYTE_READ_ERROR = -1;
63
64     private static String JavaDoc basedir = null;
65
66     /* -------------------------------------------------------------------------------------
67     */

68     
69     public static File getTempDirectory() {
70     String JavaDoc temp = System.getProperty("java.io.tmpdir");
71     String JavaDoc home = System.getProperty("user.name");
72     if (home == null) {
73         home = ""; // <-- may not be the best choice for the default value
74
}
75         File tmp = null;
76     if (temp == null) {
77             tmp = new File(home, "tmp");
78     } else {
79             tmp = new File(temp, "j2ee-ri-" + home);
80         }
81         if (!tmp.exists()) {
82             tmp.mkdirs();
83         }
84     return tmp;
85     }
86
87     /**
88     * This method converts a relative file path to an absolute path
89     * using the system property "com.sun.enterprise.home" as the server root.
90     * If the property "com.sun.enterprise.home" has not been found,
91     * it will look for j2ee.jar under classpath to find out server root
92     * If still cannot find it, it assumes
93     * that the current working directory as the server root.
94     * The relative paths specify UNIX file name separator conventions.
95     * @param A path relative to the server root.
96     * @return An absolute file path.
97     */

98
99     public static String JavaDoc getAbsolutePath(String JavaDoc relativePath)
100     {
101     if(isAbsolute(relativePath))
102         return relativePath;
103
104     String JavaDoc rpath = relativePath.replace('/', File.separatorChar);
105         if (basedir == null) setBaseDir();
106     String JavaDoc path = basedir + File.separator + relativePath;
107
108     return new File(path).getAbsolutePath();
109     }
110
111     private static void setBaseDir() {
112         // use com.sun.enterprise.home property if defined
113
basedir = System.getProperty(HOME_DIR_PROP);
114         if (basedir != null) {
115             return;
116         } else {
117             basedir = DEFAULT_HOME_DIR;
118         }
119         // look for j2ee.jar under java.class.path
120
String JavaDoc classPath = System.getProperty("java.class.path");
121         if (classPath == null) {
122             return;
123         } else {
124             StringTokenizer st =
125                 new StringTokenizer(classPath, File.pathSeparator);
126             while (st.hasMoreTokens()) {
127                 String JavaDoc filename = st.nextToken();
128                 if (filename.endsWith(JAR_FILE_NAME)) {
129                     try {
130                         // found j2ee.jar, cd .. for j2ee root
131
String JavaDoc parent =
132                             (new File(filename)).getAbsoluteFile().
133                             getParentFile().getParent();
134                         if (parent != null) {
135                             basedir = parent;
136                         }
137                         return;
138                     } catch (NullPointerException JavaDoc ex) {
139                         // cannot go up directories
140
return;
141                     }
142                 }
143             }
144         }
145     }
146
147     private static boolean isAbsolute(String JavaDoc fpath)
148     {
149     return new File(fpath).isAbsolute();
150     }
151
152     /*****
153     // Return the full path name of a file in the lib directory.
154     public static String getFullPathFor(String filename)
155     {
156     // j2ee.jar is assumed to be in the lib directory
157     // So first get the directory for j2ee.jar
158         URL url = FileUtil.class.getResource("/jndi.properties");
159         if (url == null) {
160             // cannot find jndi.properties
161             // probably due to security restriction
162             throw new SecurityException("Cannot find jndi.properties, possibly due to security restriction.");
163         }
164
165         String jndiprops = url.getFile();
166         // jndiprops is of the format:
167         // "file:/blah/blah/j2ee.jar!/jndi.properties" on Solaris
168         // "file:/C:/blah/blah/j2ee.jar!/jndi.properties" on Windows NT
169         String jardir = jndiprops.substring(5, jndiprops.indexOf(JAR_FILE_NAME));
170     return jardir+filename;
171     }
172     *****/

173     
174     /**
175     * Return a set of all the files (File objects) under the directory specified, with
176     * relative pathnames filtered with the filename filter (can be null for all files).
177     */

178     public static Set getAllFilesUnder(File directory, FilenameFilter JavaDoc filenameFilter) throws IOException JavaDoc {
179     if (!directory.exists() || !directory.isDirectory()) {
180         throw new IOException JavaDoc("Problem with: " + directory + ". You must supply a directory that exists");
181     }
182         return getAllFilesUnder(directory, filenameFilter, true);
183     }
184
185     public static Set getAllFilesUnder(File directory, FilenameFilter JavaDoc filenameFilter, boolean relativize) throws IOException JavaDoc {
186         Set allFiles = new TreeSet();
187         File relativizingDir = relativize ? directory : null;
188         recursiveGetFilesUnder( relativizingDir, directory, filenameFilter,
189                                 allFiles, false );
190         return allFiles;
191     }
192
193     public static Set getAllFilesAndDirectoriesUnder(File directory) throws IOException JavaDoc {
194     if (!directory.exists() || !directory.isDirectory()) {
195         throw new IOException JavaDoc("Problem with: " + directory + ". You must supply a directory that exists");
196     }
197     Set allFiles = new TreeSet();
198     recursiveGetFilesUnder(directory, directory, null, allFiles, true);
199     return allFiles;
200     }
201     
202     // relativizingRoot can be null, in which case no relativizing is
203
// performed.
204
private static void recursiveGetFilesUnder(File relativizingRoot, File directory, FilenameFilter JavaDoc filenameFilter, Set set, boolean returnDirectories) {
205     File[] files = directory.listFiles(filenameFilter);
206     for (int i = 0; i < files.length; i++) {
207         if (files[i].isDirectory()) {
208         recursiveGetFilesUnder(relativizingRoot, files[i], filenameFilter, set, returnDirectories);
209         if (returnDirectories) {
210                     if( relativizingRoot != null ) {
211                         set.add(relativize(relativizingRoot, files[i]));
212                     } else {
213                         set.add(files[i]);
214                     }
215         }
216         } else {
217                 if( relativizingRoot != null ) {
218                     set.add(relativize(relativizingRoot, files[i]));
219                 } else {
220                     set.add(files[i]);
221                 }
222         }
223         }
224     }
225     
226     /**
227      * Given a directory and a fully-qualified file somewhere
228      * under that directory, return the portion of the child
229      * that is relative to the parent.
230      */

231     public static File relativize(File parent, File child) {
232     String JavaDoc baseDir = parent.getAbsolutePath();
233     String JavaDoc baseDirAndChild = child.getAbsolutePath();
234
235         String JavaDoc relative = baseDirAndChild.substring(baseDir.length(),
236                                                     baseDirAndChild.length());
237
238         // Strip off any extraneous file separator character.
239
if( relative.startsWith(File.separator) ) {
240             relative = relative.substring(1);
241         }
242
243     return new File(relative);
244     }
245
246     /**
247      * Convert the zip entry name of a java .class file to its
248      * class name. E.g. "hello/Hello.class" would be converted
249      * to "hello.Hello"
250      * Entry is assumed to end in ".class". If it doesn't, the
251      * entry name is returned as is.
252      * @param Zip entry name for a .class file
253      */

254     public static String JavaDoc classNameFromEntryName(String JavaDoc entryName) {
255         String JavaDoc className = entryName;
256         if( entryName.endsWith(".class") ) {
257             int dotClassIndex = entryName.indexOf(".class");
258             className = entryName.substring(0, dotClassIndex);
259             className = className.replace(JAR_SEPARATOR_CHAR , '.');
260         }
261         return className;
262     }
263
264     /**
265      * Convert the file name of a .class file to a class name.
266      * E.g. "hello\Hello.class" would be converted
267      * to "hello.Hello"
268      * File is assumed to end in ".class". If it doesn't, the
269      * file name is returned as is.
270      * @param File name of a .class file
271      */

272     public static String JavaDoc classNameFromFile(File file) {
273         String JavaDoc className = file.toString();
274         if ( className.endsWith(".class") ) {
275             String JavaDoc contentFileStr = className.replace(File.separatorChar, '.');
276             int cutOffPoint = contentFileStr.lastIndexOf(".class");
277             className = contentFileStr.substring(0, cutOffPoint);
278         }
279         return className;
280     }
281     
282
283     public static void copyFile(File sourceFile, File destFile)
284         throws IOException JavaDoc {
285
286         File parent = new File(destFile.getParent());
287         if (!parent.exists()) {
288             parent.mkdirs();
289         }
290
291         FileInputStream fis = new FileInputStream(sourceFile);
292         FileChannel in = fis.getChannel();
293         FileOutputStream fos = new FileOutputStream(destFile);
294         FileChannel out = fos.getChannel();
295         in.transferTo(0, in.size(), out);
296         in.close();out.close();fis.close();fos.close();
297     }
298
299     /**
300      * Return an array of filenames from a colon-separated
301      * list of filenames
302      */

303     public static String JavaDoc[] parseFileList(String JavaDoc files) {
304
305         Vector fileNames = new Vector();
306         boolean checkDriveLetter = !(File.pathSeparator.equals(":"));
307         StringTokenizer st = new StringTokenizer(files, ":");
308         while(st.hasMoreTokens()) {
309             String JavaDoc name = st.nextToken();
310             if (checkDriveLetter && name.length() == 1) {
311                 // short-term fix for bug 4262319
312
// win32 filename might include ':' (e.g. c:\myapp.jar)
313
if (st.hasMoreTokens()) {
314                     name = name + ":" + st.nextToken();
315                 }
316             }
317             fileNames.addElement(name);
318         }
319         int size = fileNames.size();
320         String JavaDoc[] result = new String JavaDoc[size];
321         for (int i=0; i< size; i++) {
322             result[i] = (String JavaDoc) fileNames.elementAt(i);
323         }
324         return result;
325     }
326
327     /**
328      * Test for equality of two jar entries.
329      */

330     public static boolean jarEntriesEqual(File file1, String JavaDoc entry1Name,
331                                           File file2, String JavaDoc entry2Name)
332         throws IOException JavaDoc {
333         boolean identical = false;
334         JarFile jarFile1 = null;
335         JarFile jarFile2 = null;
336
337         try {
338             jarFile1 = new JarFile(file1);
339             jarFile2 = new JarFile(file2);
340
341             // Jar entries always use '/'.
342
String JavaDoc jarEntry1Name = entry1Name.replace(File.separatorChar,
343                                                       JAR_SEPARATOR_CHAR);
344             String JavaDoc jarEntry2Name = entry2Name.replace(File.separatorChar,
345                                                       JAR_SEPARATOR_CHAR);
346
347             JarEntry entry1 = jarFile1.getJarEntry(jarEntry1Name);
348             JarEntry entry2 = jarFile2.getJarEntry(jarEntry2Name);
349
350             if( entry1 == null ) {
351         /** IASRI 4660742
352         if( debug ) {
353             System.out.println(file1 + ":" + entry1Name + " not found");
354         }
355         **/

356         // START OF IASRI 4660742
357
if(debug && _logger.isLoggable(Level.FINE)) {
358             _logger.log(Level.FINE,file1 + ":" + entry1Name + " not found");
359         }
360         // END OF IASRI 4660742
361

362         }
363         else if( entry2 == null ) {
364         /** IASRI 4660742
365         if( debug ) {
366             System.out.println(file2 + ":" + entry2Name + " not found");
367         }
368         **/

369         // START OF IASRI 4660742
370
if(debug && _logger.isLoggable(Level.FINE)) {
371             _logger.log(Level.FINE,file2 + ":" + entry2Name + " not found");
372         }
373         // END OF IASRI 4660742
374
}
375         else {
376         identical = jarEntriesEqual(jarFile1, entry1, jarFile2, entry2);
377         }
378         if( debug ) {
379         /** IASRI 4660742
380         System.out.println("Are " + entry1Name + " and " + entry2Name +
381         " identical? " + ( identical ? "YES" : "NO"));
382         **/

383         // START OF IASRI 4660742
384
if(_logger.isLoggable(Level.FINE)) {
385             _logger.log(Level.FINE, "Are " + entry1Name + " and "
386             + entry2Name + " identical? " + ( identical ? "YES" : "NO"));
387         }
388         // END OF IASRI 4660742
389
}
390     } catch(IOException JavaDoc e) {
391         if( debug ) {
392         /** IASRI 4660742
393         e.printStackTrace();
394         **/

395         // START OF IASRI 4660742
396
if(_logger.isLoggable(Level.WARNING))
397             _logger.log(Level.WARNING,"enterprise_util.excep_in_fileutil",e);
398             // END OF IASRI 4660742
399
}
400         throw e;
401     }
402     finally {
403         if( jarFile1 != null ) {
404         jarFile1.close();
405         }
406         if( jarFile2 != null ) {
407         jarFile2.close();
408         }
409     }
410     
411     return identical;
412     }
413
414     /**
415      * Test for equality of two jar entries.
416      * NOTE : Not yet optimized for large-file comparisons.
417      * @@@ TODO : Read bytes in chunks.
418      */

419     public static boolean jarEntriesEqual(JarFile jarFile1, JarEntry entry1,
420                                           JarFile jarFile2, JarEntry entry2)
421         throws IOException JavaDoc
422     {
423         boolean identical = false;
424         int entry1Size = (int) entry1.getSize();
425         int entry2Size = (int) entry2.getSize();
426            
427         if( (entry1Size == JAR_ENTRY_UNKNOWN_VALUE) ||
428             (entry2Size == JAR_ENTRY_UNKNOWN_VALUE) ||
429             (entry1Size == entry2Size) ) {
430
431             // Both files are 0 bytes long.
432
if( entry1Size == 0 ) {
433                 return true;
434             }
435
436             InputStream inputStream1 = null;
437             InputStream inputStream2 = null;
438             try {
439                 inputStream1 = jarFile1.getInputStream(entry1);
440                 inputStream2 = jarFile2.getInputStream(entry2);
441
442                 byte[] file1Bytes = new byte[entry1Size];
443                 byte[] file2Bytes = new byte[entry2Size];
444                 
445                 int read=0;
446                 int numBytesRead1=0;
447                 do {
448                     read = inputStream1.read(file1Bytes, numBytesRead1, entry1Size-numBytesRead1);
449                     numBytesRead1 += read;
450                 } while (read!=BYTE_READ_ERROR & numBytesRead1!=entry1Size);
451                 
452                 int numBytesRead2=0;
453                 do {
454                     read = inputStream2.read(file2Bytes, numBytesRead2, entry2Size-numBytesRead2);
455                     numBytesRead2 += read;
456                 } while (read!=BYTE_READ_ERROR & numBytesRead2!=entry2Size);
457                 
458                
459                 if( ( numBytesRead1 == BYTE_READ_ERROR ) ||
460                     ( numBytesRead2 == BYTE_READ_ERROR ) ) {
461                     throw new IOException JavaDoc("Byte read error " + numBytesRead1 + " " + numBytesRead2);
462                 }
463                 else if( Arrays.equals(file1Bytes, file2Bytes) ) {
464                     identical = true;
465                 }
466                 else {
467             /** IASRI 4660742
468             if( debug ) { System.out.println("bytes not equal"); }
469             **/

470             // START OF IASRI 4660742
471
if(debug) {
472             _logger.log(Level.FINE,"bytes not equal");
473             }
474             // END OF IASRI 4660742
475

476                 }
477             } catch(IOException JavaDoc e) {
478                 /** IASRI 4660742
479                     if( debug ) { e.printStackTrace(); }
480                     **/

481                     // START OF IASRI 4660742
482
if (debug && _logger.isLoggable(Level.WARNING)) {
483                     _logger.log(Level.WARNING,"enterprise_util.excep_in_fileutil",e);
484                  }
485                 // END OF IASRI 4660742
486

487                 throw e;
488             } finally {
489                 if( inputStream1 != null ) { inputStream1.close(); }
490                 if( inputStream2 != null ) { inputStream2.close(); }
491             }
492         }
493         else {
494               /** IASRI 4660742
495             if( debug ) {
496                 System.out.println("sz: " + entry1Size + " , " + entry2Size);
497             }
498               **/

499             // START OF IASRI 4660742
500
if(debug && _logger.isLoggable(Level.FINE)) {
501                    _logger.log(Level.FINE,"sz: " + entry1Size + " , " + entry2Size);
502             }
503             // END OF IASRI 4660742
504

505         }
506         return identical;
507     }
508
509         /* -------------------------------------------------------------------------------------
510     */

511
512     public static boolean isEARFile(File file) {
513         try {
514             JarFile jar = new JarFile(file);
515             ZipEntry JavaDoc result = jar.getEntry("META-INF/application.xml");
516             jar.close();
517             return result != null;
518         } catch (IOException JavaDoc ex) {
519             return false;
520         }
521     }
522
523
524     public static boolean isWARFile(File file) {
525         try {
526             JarFile jar = new JarFile(file);
527             ZipEntry JavaDoc result = jar.getEntry("WEB-INF/web.xml");
528             jar.close();
529             return result != null;
530         } catch (IOException JavaDoc ex) {
531             return false;
532         }
533     }
534
535     public static boolean isEJBJar(File file) {
536         try {
537             JarFile jar = new JarFile(file);
538             ZipEntry JavaDoc result = jar.getEntry("META-INF/ejb-jar.xml");
539             jar.close();
540             return result != null;
541         } catch (IOException JavaDoc ex) {
542             return false;
543         }
544     }
545
546     public static boolean isRARFile(File file) {
547         try {
548             JarFile jar = new JarFile(file);
549             ZipEntry JavaDoc result = jar.getEntry("META-INF/ra.xml");
550             jar.close();
551             return result != null;
552         } catch (IOException JavaDoc ex) {
553             return false;
554         }
555     }
556
557     public static boolean isAppClientJar(File file) {
558         try {
559             JarFile jar = new JarFile(file);
560             ZipEntry JavaDoc result = jar.getEntry("META-INF/application-client.xml");
561             jar.close();
562             return result != null;
563         } catch (IOException JavaDoc ex) {
564             return false;
565         }
566     }
567     
568     /**
569      * Deletes all contained files/dirs in specified dir (does _not_ delete 'dir')
570      * Returns true if all contents was successfully deleted
571      * This specifically checks to make sure it isn't following symbolic links
572      */

573     public static boolean deleteDirContents(File dir)
574     {
575
576         if (dir.isDirectory()) {
577
578         try {
579         boolean ok = true;
580             File dirCon = dir.getCanonicalFile();
581                 String JavaDoc ch[] = dirCon.list();
582                 for (int i = 0; i < ch.length; i++) {
583             File file = new File(dir, ch[i]);
584             try {
585                 File fileCon = file.getCanonicalFile(); // may throw IOException
586
if (fileCon.getParentFile().equals(dirCon)) {
587                 // file is a proper child of the parent directory
588
if (!FileUtil.delete(fileCon)) { ok = false; }
589             } else {
590                 // This indicates that the actual child file is not part of the
591
// parent directory, likely because 'ch[i]' represents a symbolic
592
// link. Calling 'file.delete()' here just deletes the symbolic
593
// link and not the file itself.
594
Print.dprintln("Symbolic link? " + file);
595                 //Print.dprintln(" => dir : " + dirCon);
596
//Print.dprintln(" => file parent: " + fileCon.getParentFile());
597
if (!file.delete()) { ok = false; } // try deleting symbolic link
598
}
599             } catch (IOException JavaDoc ioe) {
600             // unable to determine canonical path of child
601
Print.dprintStackTrace("Can't delete: " + file, ioe);
602             ok = false;
603             }
604         }
605         return ok;
606             } catch (IOException JavaDoc ioe) {
607         // unable to determine canonical path of parent dir
608
Print.dprintStackTrace("Can't delete dir contents: " + dir, ioe);
609         return false;
610         }
611
612         }
613
614     return false;
615
616     }
617
618     /**
619      * Deletes all files and subdirectories under dir.
620      * Returns true if the specified file/dir was deleted
621      * This specifically checks to make sure it isn't following symbolic links
622      */

623     public static boolean deleteDir(File fileDir) {
624     return FileUtil.delete(fileDir);
625     }
626
627
628     public static URL JavaDoc getEntryAsUrl(File moduleLocation, String JavaDoc uri)
629         throws MalformedURLException JavaDoc, IOException JavaDoc {
630         URL JavaDoc url = null;
631         try {
632             url = new URL JavaDoc(uri);
633         } catch(java.net.MalformedURLException JavaDoc e) {
634             // ignore
635
url = null;
636         }
637         if (url!=null) {
638             return url;
639         }
640         if( moduleLocation != null ) {
641             if( moduleLocation.isFile() ) {
642                 url = FileUtil.createJarUrl(moduleLocation, uri);
643             } else {
644                 String JavaDoc path = uri.replace('/', File.separatorChar);
645                 url = new File(moduleLocation, path).toURI().toURL();
646             }
647         }
648         return url;
649     }
650
651     public static URL JavaDoc createJarUrl(File jarFile, String JavaDoc entry)
652         throws MalformedURLException JavaDoc, IOException JavaDoc {
653         return new URL JavaDoc("jar:" + jarFile.toURI().toURL() + "!/" + entry);
654     }
655
656     /**
657      * Deletes all files and subdirectories under dir.
658      * Returns true if the specified file/dir was deleted
659      */

660     public static boolean delete(File dir) {
661         if (dir.isDirectory()) {
662         FileUtil.deleteDirContents(dir);
663             return dir.delete(); // delete directory (only if it's empty)
664
// If this delete fails, it's likely due to one of the following:
665
// - Improper permissions.
666
// - On Unix, it's possible that the deleted content files were turned
667
// into a bunch of '.nfsXXXX' files. Thus this dir was not empty
668
// and could not be deleted.
669
// - One of the content files failed to be deleted (see below)
670
} else {
671             return dir.delete(); // delete file
672
// If this delete fails, it's likely due to one of the following:
673
// - Improper permissions.
674
// - Didn't exist.
675
}
676     }
677
678     /* -------------------------------------------------------------------------------------
679     */

680
681     private static final boolean DeleteOnExit_ShutdownHook = true;
682
683     private static Vector deleteOnExit_normal = null;
684     private static Vector deleteOnExit_forced = null;
685
686     /*
687     ** delete specified file on exit
688     ** if specified file is a directory, delete the directory only if
689     ** it is empty
690     */

691     public static File deleteOnExit(File file) {
692     return deleteOnExit(file, false);
693     }
694
695     /*
696     ** delete specified file on exit
697     ** if specified file is a directory and 'forceDeleteDir' is true, then
698     ** delete the contents of the directory, followed by the directory itself.
699     */

700     public static File deleteOnExit(File file, boolean forceDeleteDir) {
701     if (DeleteOnExit_ShutdownHook) {
702         if (!file.isAbsolute()) {
703         Print.dprintStackTrace("File is not Absolute! " + file.toString());
704         } else {
705             if (deleteOnExit_forced == null) {
706             deleteOnExit_forced = new Vector();
707             deleteOnExit_normal = new Vector();
708             Runtime.getRuntime().addShutdownHook(new Thread JavaDoc() {
709                 public void run() {
710                 _delFiles(deleteOnExit_forced, true);
711                 _delFiles(deleteOnExit_normal, false);
712             }
713             });
714             }
715         if (forceDeleteDir && file.isDirectory()) {
716             if (!deleteOnExit_forced.contains(file)) {
717                 deleteOnExit_forced.add(file);
718             }
719         } else {
720             if (!deleteOnExit_normal.contains(file)) {
721                 deleteOnExit_normal.add(file);
722             }
723         }
724         }
725     } else {
726         file.deleteOnExit();
727     }
728     return file;
729     }
730
731     private static void _delFiles(java.util.List JavaDoc list, boolean forceDelete) {
732     if (list == null) {
733         return;
734     }
735
736     /* sort list from longest to shortest */
737     if (!forceDelete) {
738         // A directory must be empty in order to be deleted.
739
// Sorting the list attempts to place files ahead of directory deletes.
740
// The quick way to accomplish this is by sorting the list of files in
741
// descending order of the length of their path. Doing so will always
742
// place files before the directory which contains them.
743
// The deletion of directories is not forced because a file may have
744
// been added to a given directory that was not marked 'deleteOnExit'.
745
// If it is preferred to delete directories which have been marked for
746
// 'deleteOnExit' regardless of whether they contain non-marked files
747
// or not, then this sort is not necessary.
748
Comparator fileComparator = new Comparator() {
749             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
750             String JavaDoc n1 = o1.toString(), n2 = o2.toString();
751             return n2.length() - n1.length();
752             }
753             public boolean equals(Object JavaDoc o) {
754             return super.equals(o);
755             }
756         };
757         Collections.sort(list, fileComparator);
758     }
759
760     /* delete files/directories */
761     for (Iterator i = list.iterator(); i.hasNext();) {
762         File file = (File)i.next();
763         if (!file.isAbsolute()) {
764         Print.dprintln("[Not Absolute!] " + file);
765         } else
766         if (file.exists()) {
767         if (forceDelete) {
768             if (!FileUtil.delete(file)) {
769                     Print.dprintln("[Not Deleted!] " + file);
770             }
771         } else {
772             // This will not delete a directory which still contains files.
773
if (!file.delete()) { // if (!FileUtil.delete(file)) {
774
Print.dprintln("[Not Deleted!] " + file);
775             }
776         }
777         } else {
778         // File/Directory no longer exists. Quietly ignore.
779
}
780     }
781
782     }
783
784     
785     public static String JavaDoc getClassNameFromFile(File f) throws IOException JavaDoc, ClassFormatError JavaDoc {
786     FileClassLoader fcl = new FileClassLoader(f.toString());
787     return fcl.getClassName(f);
788     }
789     
790 }
791
Popular Tags