KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > misc > FileUtil


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64 /*
65  * FileUtil.java
66  *
67  * Copyright 1999, 2000, 2001 Jcorporate Ltd.
68  */

69 package com.jcorporate.expresso.core.misc;
70
71 import com.jcorporate.expresso.core.db.DBException;
72 import com.jcorporate.expresso.services.dbobj.Setup;
73 import org.apache.log4j.Logger;
74
75 import java.io.BufferedInputStream JavaDoc;
76 import java.io.BufferedOutputStream JavaDoc;
77 import java.io.BufferedReader JavaDoc;
78 import java.io.File JavaDoc;
79 import java.io.FileInputStream JavaDoc;
80 import java.io.FileOutputStream JavaDoc;
81 import java.io.IOException JavaDoc;
82 import java.io.InputStream JavaDoc;
83 import java.io.InputStreamReader JavaDoc;
84 import java.io.OutputStream JavaDoc;
85 import java.util.Enumeration JavaDoc;
86 import java.util.StringTokenizer JavaDoc;
87 import java.util.Vector JavaDoc;
88
89
90 /**
91  * Utilities for manipulations of disk files
92  *
93  * @author Michael Nash
94  */

95 public class FileUtil {
96     private static String JavaDoc thisClass = FileUtil.class + ".";
97
98     private static Logger log = Logger.getLogger(FileUtil.class);
99
100     /**
101      * Constructor
102      */

103     public FileUtil() {
104         super();
105     }
106     /* FileUtil() */
107
108
109     /**
110      * Retrieve the temp directory in the form of a java.io.File object. This
111      * then can be used as a 'parent' for creating files within that directory
112      * via the createTempFile factory method in java.io.File.
113      *
114      * @param dataContext the location to look for the setup table
115      * @return File instance
116      * @throws ConfigurationException if the specified data context cannot be
117      * found
118      */

119     public static File JavaDoc getTempDirectory(String JavaDoc dataContext) throws ConfigurationException {
120         try {
121             String JavaDoc templocation = Setup.getValueRequired(dataContext, "TempDir");
122             File JavaDoc f = new File JavaDoc(templocation);
123             if (f != null) {
124                 if (f.isFile()) {
125                     throw new ConfigurationException("Location: " + templocation
126                             + " is a file not a directory");
127                 } else if (!f.exists()) {
128                     f.mkdirs();
129                     return f;
130                 } else if (f.isDirectory()) {
131                     return f;
132                 } else {
133                     throw new ConfigurationException("Location " + templocation +
134                             " is listed as neither a file nor a directory.");
135                 }
136             } else {
137                 throw new ConfigurationException("Unable to create java.io.File object");
138             }
139         } catch (DBException ex) {
140             throw new ConfigurationException("Unable to locate temp directory for Expresso"
141                     , ex);
142         }
143     }
144
145     /**
146      * Get the base filename of a file (e.g. no directory or extension)
147      *
148      * @param fileName Original pathname to get the base name from. IMPORTANT:
149      * This method assumes that "/" is the directory seperator, not
150      * &quot;\&quot;!!!
151      * @return String The base file name
152      */

153     public static String JavaDoc getBase(String JavaDoc fileName) {
154
155         String JavaDoc tempName1;
156
157         int val = fileName.lastIndexOf("/");
158         if (val < 0) {
159             val = fileName.lastIndexOf("\\");
160         }
161
162         if (val < 0) {
163             tempName1 = fileName;
164         } else {
165             tempName1 = fileName.substring(val + 1);
166         }
167
168         if (tempName1 == null || tempName1.length() == 0) {
169             return null;
170         }
171
172         val = tempName1.indexOf(".");
173
174         if (val > 0) {
175             tempName1 = tempName1.substring(0, val);
176         } else if (val == 0) {
177             tempName1 = "";
178         }
179
180         return tempName1;
181     }
182     /* getBase(String) */
183
184     /**
185      * Return a vector of the file/dir names in any give directory
186      *
187      * @param dirName the name of the directory to retrieve a list of all files
188      * @return Vector of strings of file names in the directory
189      * @throws IOException If the given name is not a directory or if an I/O
190      * error occurs when trying to read the file list
191      */

192     public static Vector JavaDoc getDir(String JavaDoc dirName) throws IOException JavaDoc {
193         String JavaDoc myName = (thisClass + "getDir(String)");
194         File JavaDoc dirFile = new File JavaDoc(dirName);
195
196         if (!dirFile.isDirectory()) {
197             throw new IOException JavaDoc(myName + ":'" + dirName +
198                     "' is not a directory.");
199         }
200
201         String JavaDoc[] dir = dirFile.list();
202
203         if (dir == null) {
204             throw new IOException JavaDoc(myName + ":Null array reading directory " +
205                     " of " + dirName);
206         }
207
208         Vector JavaDoc fileList = new Vector JavaDoc(1);
209         String JavaDoc oneFileName = null;
210
211         for (int i = 0; i < dir.length; i++) {
212             oneFileName = dir[i].trim();
213             fileList.addElement(oneFileName);
214         }
215
216         return fileList;
217     }
218     /* getDir(String) */
219
220     /**
221      * Return a vector of the recursive listing of the file names starting from in any given directory
222      *
223      * @param dirName the name of the directory to retrieve a list of all files in that directory and it's sub-directories
224      * @param prefix a string to prepend to the path
225      * @param includeExtension List of strings of files to be included. All are included if the list is null.
226      * @param pathSeparator The separator is the character which will be used to represent directory name-space (usually "/" or "\\")
227      * @return List of strings of file names in the directory and sub-directories
228      * @throws IOException If the given dirName is not a directory or if an I/O
229      * error occurs when trying to read the file list
230      */

231     public static Vector JavaDoc getFileListingRecursive(String JavaDoc dirName,
232                                                  String JavaDoc prefix,
233                                                  String JavaDoc separator,
234                                                  Vector JavaDoc includeExtension) throws IOException JavaDoc {
235         String JavaDoc myName = (thisClass + "getFileListingRecursive(String,String,String,Vector)");
236
237         File JavaDoc dirFile = new File JavaDoc(dirName);
238
239         if (!dirFile.isDirectory()) {
240             throw new IOException JavaDoc(myName + ":'" + dirName +
241                     "' is not a directory.");
242         }
243
244         File JavaDoc[] dir = dirFile.listFiles();
245
246         if (dir == null) {
247             throw new IOException JavaDoc(myName + ":Null array reading directory " +
248                     " of " + dirName);
249         }
250
251         Vector JavaDoc fileList = new Vector JavaDoc(1);
252         String JavaDoc oneFileName = null;
253
254         String JavaDoc prefixToAdd = "";
255         if (!StringUtil.isBlankOrNull(prefix)) {
256             prefixToAdd = prefix + separator;
257         }
258
259         for (int i = 0; i < dir.length; i++) {
260             if (dir[i].isDirectory()) {
261                 fileList.addAll(getFileListingRecursive(dir[i].getAbsolutePath(), prefixToAdd + dir[i].getName(), separator,
262                         includeExtension));
263             } else {
264                 if (includeExtension == null || includeExtension.contains(getExtension(dir[i].getName()))) {
265                     oneFileName = dir[i].getName();
266                     fileList.add(prefixToAdd + oneFileName);
267                 }
268             }
269         }
270
271         return fileList;
272     }
273
274     /**
275      * Get the file extension (after the ".")
276      *
277      * @param fileName Original full file name
278      * @return String Extension name
279      */

280     public static String JavaDoc getExtension(String JavaDoc fileName) {
281         String JavaDoc tempName = new File JavaDoc(fileName).getName();
282         StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(tempName, ".");
283         stk.nextToken();
284
285         if (stk.hasMoreTokens()) {
286             String JavaDoc ext;
287             do {
288                 ext = stk.nextToken();
289             } while (stk.hasMoreTokens());
290
291             return ext;
292         } else {
293             return ("");
294         }
295     }
296     /* getExtension(String) */
297
298     /**
299      * Get the path of a file name
300      *
301      * @param fileName Original pathname
302      * @return String Path portion of the pathname
303      */

304     public static String JavaDoc getPath(String JavaDoc fileName) {
305         if (fileName == null || fileName.length() == 0) {
306             return fileName;
307         }
308
309         int val = fileName.lastIndexOf("/");
310         if (val < 0) {
311             val = fileName.lastIndexOf("\\");
312         }
313
314         String JavaDoc tempPath;
315         if (val < 0) {
316             return fileName;
317         } else {
318             tempPath = fileName.substring(0, val);
319         }
320
321         return tempPath;
322     }
323     /* getPath(String) */
324
325     /**
326      * CleanDirs is a utility method for cleaning up temporary directories,
327      * used by various methods to hold & process files on the file system.
328      * CleanDir takes a directory name as an argument, and checks for any
329      * empty directories within that directory. If it finds any, it remove the
330      * empty directory & checks again until no empty directories are found.
331      *
332      * @param fileName the name of the directory to clean
333      * @throws IOException upon error
334      */

335     public static void cleanDirs(String JavaDoc fileName) throws IOException JavaDoc {
336         if (log.isDebugEnabled()) {
337             log.debug("Cleaning " + fileName);
338         }
339
340         if (!fileName.endsWith("/")) {
341             fileName = fileName + "/";
342         }
343
344         Vector JavaDoc contents = getDir(fileName);
345         String JavaDoc oneItem = null;
346         File JavaDoc oneFile = null;
347
348         for (Enumeration JavaDoc e = contents.elements(); e.hasMoreElements();) {
349             oneItem = (String JavaDoc) e.nextElement();
350             oneFile = new File JavaDoc(fileName + oneItem);
351
352             /* If it's a directory.... */
353             if (oneFile.isDirectory()) {
354                 if (log.isDebugEnabled()) {
355                     log.debug("Cleaning subdirectory " + fileName + oneItem);
356                 }
357
358                 /* Try cleaning it */
359                 cleanDirs(fileName + oneItem);
360
361                 /* If it's now empty... */
362                 if (getDir(fileName + oneItem).size() == 0) {
363                     oneFile = new File JavaDoc(fileName + oneItem);
364                     log.info("Deleting empty directory " + oneItem);
365
366                     /* Zap it ... */
367                     if (!oneFile.delete()) {
368                         log.error("Unable to delete directory " + oneItem);
369                     }
370                     /* if we were unable to delete */
371                 }
372                 /* if the dir is now empty */
373             }
374             /* if the entry is a directory */
375         }
376         /* for each entry in the directory */
377     }
378     /* cleanDirs(String) */
379
380     /**
381      * Utility method to copy a file from one place to another & delete the
382      * original. We do this in order to preserve directory security, which is
383      * not preserved under NT if we simply move the file (with a renameTo) If
384      * we fail, we throw IOException, also reporting what user this process is
385      * running with to assist System Admins in setting appropriate permissions
386      *
387      * @param sourceFile Source file pathname
388      * @param destFile Destination file pathname
389      * @throws IOException If the copy fails due to an I/O error
390      */

391     public static void copyFile(String JavaDoc sourceFile, String JavaDoc destFile)
392             throws IOException JavaDoc {
393         String JavaDoc myName = (thisClass + "copyFile(String, String)");
394
395         if (sourceFile.equals("")) {
396             throw new IOException JavaDoc(myName + ":Source file name empty - cannot" +
397                     " copy.");
398         }
399
400         if (destFile.equals("")) {
401             throw new IOException JavaDoc(myName + ":Destination file name empty - " +
402                     "cannot copy.");
403         }
404
405         int onechar = 0;
406
407         if (sourceFile.equals(destFile)) {
408             throw new IOException JavaDoc(myName + ":Cannot copy file '" + sourceFile +
409                     "' to itself");
410         }
411
412         File JavaDoc dest = new File JavaDoc(destFile);
413         dest.mkdirs();
414
415         if (dest.exists()) {
416             if (!dest.delete()) {
417                 throw new IOException JavaDoc(myName + ":Unable to delete existing " +
418                         "destination file '" + destFile + "'. Logged in as " +
419                         System.getProperty("user.name"));
420             }
421         }
422
423         File JavaDoc source = new File JavaDoc(sourceFile);
424
425         if (!source.exists()) {
426             throw new IOException JavaDoc(myName + ":Source file '" + sourceFile +
427                     "' does not exist. Cannot copy. Logged in as " +
428                     System.getProperty("user.name"));
429         }
430
431         BufferedInputStream JavaDoc bin = null;
432         BufferedOutputStream JavaDoc bout = null;
433
434         try {
435             bin = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(sourceFile));
436             bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(destFile));
437
438             onechar = bin.read();
439
440             while (onechar != -1) {
441                 bout.write(onechar);
442                 onechar = bin.read();
443             }
444         } finally {
445             if (bin != null) {
446                 bin.close();
447             }
448
449             if (bout != null) {
450                 bout.close();
451             }
452         }
453
454         if (!dest.exists()) {
455             throw new IOException JavaDoc(myName +
456                     ":File copy failed: destination file" + " '" + destFile +
457                     "' does not exist after copy.");
458         }
459
460         /* The below test is commented out because it does not */
461         /* appear to work correctly under Windows NT and Windows 2000 */
462
463         //if (source.length() != dest.length()) {
464
// throw new IOException(myName + ":File copy complete, but source "
465
// + " file was " + source.length() + " bytes, destination "
466
// + " now " + dest.length() + " bytes.");
467
//}
468
}
469     /* copyFile(String, String) */
470
471     /**
472      * Command line interface to run specific items [Also used for unit testing]
473      *
474      * @param args the command line arguments
475      */

476     public static void main(String JavaDoc[] args) {
477         System.out.println("FileUtil Test");
478
479         String JavaDoc command = ("");
480         BufferedReader JavaDoc ds = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
481
482         try {
483             while (!command.equals("0")) {
484                 menu();
485                 System.out.print("Command==>");
486                 command = ds.readLine();
487                 System.out.println("");
488                 System.out.println("Command:" + command);
489
490                 if (command.equals("1")) {
491                     System.out.println("copyFile");
492                     System.out.print("sourceFile:");
493
494                     String JavaDoc sourceFile = ds.readLine();
495                     System.out.print("destFile:");
496
497                     String JavaDoc destFile = ds.readLine();
498                     copyFile(sourceFile, destFile);
499                     System.out.println("Copy Complete\n\n");
500                 } else if (command.equals("2")) {
501                     System.out.println("moveFile");
502                     System.out.print("sourceFile:");
503
504                     String JavaDoc sourceFile = ds.readLine();
505                     System.out.print("destFile:");
506
507                     String JavaDoc destFile = ds.readLine();
508                     moveFile(sourceFile, destFile);
509                     System.out.println("Move Complete\n\n");
510                 } else if (command.equals("3")) {
511                     System.out.println("getPath");
512                     System.out.print("fileName:");
513
514                     String JavaDoc fileName = ds.readLine();
515                     System.out.println("Path:'" + getPath(fileName) + "'\n\n");
516                 } else if (command.equals("4")) {
517                     System.out.println("getBase");
518                     System.out.print("fileName:");
519
520                     String JavaDoc fileName = ds.readLine();
521                     System.out.println("Base:'" + getBase(fileName) + "'\n\n");
522                 } else if (command.equals("5")) {
523                     System.out.println("getExtension");
524                     System.out.print("fileName:");
525
526                     String JavaDoc fileName = ds.readLine();
527                     System.out.println("Extension:'" + getExtension(fileName) +
528                             "'\n\n");
529                 } else if (command.equals("6")) {
530                     System.out.println("getDir");
531                     System.out.print("dirName:");
532
533                     String JavaDoc dirName = ds.readLine();
534                     Vector JavaDoc v = getDir(dirName);
535
536                     for (Enumeration JavaDoc e = v.elements(); e.hasMoreElements();) {
537                         System.out.println("Item:'" + (String JavaDoc) e.nextElement() +
538                                 "'");
539                     }
540
541                     System.out.println("Directory Complete");
542                 } else if (command.equals("7")) {
543                     System.out.println("cleanDirs");
544                     System.out.println("dirName:");
545
546                     String JavaDoc dirName = ds.readLine();
547                     cleanDirs(dirName);
548                 } else if (command.equals("8")) {
549                     System.out.println("prefix:");
550
551                     String JavaDoc prefix = ds.readLine();
552                     System.out.println("fileName:");
553
554                     String JavaDoc fileName = ds.readLine();
555                     System.out.println("Converted name:" +
556                             makeAbsolutePath(prefix, fileName));
557                 } else if (!command.equals("0")) {
558                     System.out.println("Unknown command:" + command);
559                 }
560             }
561         } catch (Exception JavaDoc e) {
562             e.printStackTrace(System.out);
563         }
564     }
565     /* main(String[]) */
566
567     /**
568      * Take a prefix and a relative path and put the two together to make an
569      * absolute path
570      *
571      * @param prefix the prefix of the path
572      * @param originalPath the original pathname
573      * @return java.lang.String the absolute path
574      */

575     public static String JavaDoc makeAbsolutePath(String JavaDoc prefix, String JavaDoc originalPath) {
576         StringUtil.assertNotBlank(originalPath,
577                 "Original path may not be blank here");
578         prefix = StringUtil.notNull(prefix);
579         originalPath = originalPath.replace('\\', '/');
580         prefix = prefix.replace('\\', '/');
581
582         if ('/' == originalPath.charAt(0)) {
583             return originalPath;
584         }
585
586         /* Check for a drive specification for windows-type path */
587         if (originalPath.substring(1, 2).equals(":")) {
588             return originalPath;
589         }
590
591         /* Otherwise... */
592         /* Make sure the prefix ends with a "/" */
593         if (!prefix.endsWith("/")) {
594             prefix = prefix + "/";
595         }
596
597         /* and put the two together */
598         return prefix + originalPath;
599     }
600     /* makeAbsolutePath(String, String) */
601
602     /**
603      * Copy a file, then remove the original file
604      *
605      * @param sourceFile Original file name
606      * @param destFile Destination file name
607      * @throws IOException If an I/O error occurs during the copy
608      */

609     public static void moveFile(String JavaDoc sourceFile, String JavaDoc destFile)
610             throws IOException JavaDoc {
611         String JavaDoc myName = (thisClass + "moveFile(String, String)");
612         File JavaDoc source = new File JavaDoc(sourceFile);
613
614         if (!source.canRead()) {
615             throw new IOException JavaDoc(myName + ":Cannot read source file '" +
616                     sourceFile + "'. Logged in as " +
617                     System.getProperty("user.name"));
618         }
619
620         if (!source.canWrite()) {
621             throw new IOException JavaDoc(myName + ":Cannot write to source file '" +
622                     sourceFile + "'. Logged in as " +
623                     System.getProperty("user.name") + ". Cannot move without " +
624                     "write permission to source file.");
625         }
626
627         if (log.isDebugEnabled()) {
628             log.debug("Moving file '" + sourceFile + "' to '" + destFile + "'");
629         }
630
631         if (sourceFile.equals(destFile)) {
632             log.error("Source and destination the same - no move " +
633                     "required");
634
635             return;
636         }
637
638         copyFile(sourceFile, destFile);
639
640         if (!new File JavaDoc(sourceFile).delete()) {
641             log.error("Copy completed, but unable to " +
642                     "delete source file '" + sourceFile + "'. Logged in as " +
643                     System.getProperty("user.name"));
644         }
645     }
646     /* moveFile(String, String) */
647
648
649     /**
650      * CopyStream does just what it says: It copies the entire contents
651      * of the input stream to the output stream by using reading and writing
652      * in 4k chunks. This particular method has been shown to be the best
653      * option for higher performance stream copying.
654      * <p/>
655      * copyStream flushes the output buffer when it has completed the copy, <b>but
656      * does not close the input stream or output stream</b>. That is the calling
657      * function's responsibility.
658      * </p>
659      *
660      * @param is the input stream for the source of the copy
661      * @param os the output stream for the sink of the copy
662      * @throws IOException upon error
663      */

664     public static void copyStream(InputStream JavaDoc is, OutputStream JavaDoc os)
665             throws java.io.IOException JavaDoc {
666         final int DEFAULT_LENGTH = 4 * 1024; //4K buffer
667

668         int optimalLength = is.available();
669
670         //
671
//If the size is huge such as > 128 Kb, or if no available() is
672
//defined, then go for the default of a 4K buffer. Otherwise,
673
//attempt the entire available() at a shot.
674
//
675
if (optimalLength > 128 * 1024 || optimalLength == 0) {
676             optimalLength = DEFAULT_LENGTH;
677         }
678
679         byte[] buf = new byte[optimalLength];
680         int bytesRead;
681
682         while ((bytesRead = is.read(buf)) != -1) {
683             os.write(buf, 0, bytesRead);
684         }
685
686         os.flush();
687     }
688
689
690     /**
691      * Generates a command menu for the command line run
692      */

693     private static void menu() {
694         System.out.println("1. copyFile");
695         System.out.println("2. moveFile");
696         System.out.println("3. getPath");
697         System.out.println("4. getBase");
698         System.out.println("5. getExtension");
699         System.out.println("6. getDir");
700         System.out.println("7. cleanDirs");
701         System.out.println("8. makeAbsolutePath");
702         System.out.println("0. quit");
703     }
704
705 }
706
707
Popular Tags