KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > diagnostics > util > FileUtils


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.diagnostics.util;
24
25 import com.sun.logging.LogDomains;
26
27 import java.nio.channels.*;
28 import java.io.*;
29 import java.util.*;
30 import java.util.logging.Level JavaDoc;
31 import java.util.logging.Logger JavaDoc;
32 import java.util.zip.*;
33 import java.util.jar.*;
34
35 /**
36  * Collection of helper methods to manipulate files.
37  */

38 public class FileUtils {
39     
40     static final int BUFFER = 2048;
41
42     private static Logger JavaDoc logger =
43             LogDomains.getLogger(LogDomains.ADMIN_LOGGER);
44
45     /**
46      * Copy source file to destination file.
47      *
48      * @param srcFile Absolute path of the source file to be copied
49      * @param destFile Absolute path of the destination file
50      *
51      */

52     public static void copyFile(String JavaDoc srcFile, String JavaDoc destFile)
53     throws IOException {
54         FileInputStream istream = new FileInputStream(srcFile);
55         File dest = new File(destFile);
56         copyFile(istream, dest);
57     }
58     
59     /**
60      * Copy contents of the specified InputStream to destination
61      * file.
62      *
63      * @param istream InputStream from which to read the source file
64      * @param destFile Absolute path of the destination file
65      *
66      */

67     public static void copyFile(InputStream istream, String JavaDoc destFile)
68     throws IOException {
69         File dest = new File(destFile);
70         copyFile(istream, dest);
71     }
72     
73     /**
74      * Copy contents of the specified InputStream to destination
75      * file.
76      *
77      * @param istream FileInputStream from which to read the source file
78      * @param destFile Absolute path of the destination file
79      *
80      */

81     public static void copyFile(FileInputStream istream, String JavaDoc destFile)
82     throws IOException {
83         File dest = new File(destFile);
84         copyFile(istream, dest);
85     }
86     
87     /**
88      * Copy contents of the specified InputStream to desintation
89      * file.
90      *
91      * @param istream InputStream from which to read the source file
92      * @param dest Destination File to copy the source file to
93      *
94      */

95     public static void copyFile(InputStream istream, File dest)
96     throws IOException {
97         OutputStream ostream = new FileOutputStream(dest);
98         dest.createNewFile();
99         copyFileToStream(istream, ostream);
100         ostream.close();
101     }
102     
103     /**
104      * Copy contents of the specified InputStream to desintation
105      * file.
106      *
107      * @param istream FileInputStream from which to read the source file
108      * @param dest Destination File to copy the source file to
109      *
110      */

111     public static void copyFile(FileInputStream istream, File dest)
112     throws IOException {
113         if (!dest.exists()) {
114             dest.getParentFile().mkdirs();
115         }
116         FileOutputStream ostream = new FileOutputStream(dest);
117         dest.createNewFile();
118         copyFileToStream(istream, ostream);
119         ostream.close();
120     }
121     
122     /**
123      * Copy file from an inputstream to a outputstream
124      *
125      * @param istream Source input stream
126      * @param ostream Destination output stream
127      *
128      */

129     public static void copyFileToStream(InputStream istream, OutputStream ostream)
130     throws IOException {
131         while(true){
132             int nextByte = istream.read();
133             if (nextByte==-1)
134                 break;
135             ostream.write(nextByte);
136         }
137         istream.close();
138     }
139     
140     /**
141      * Copy file from an file inputstream to a file outputstream
142      *
143      * @param istream Source input stream
144      * @param ostream Destination output stream
145      *
146      */

147     public static void copyFileToStream(FileInputStream istream, FileOutputStream ostream)
148     throws IOException {
149         FileChannel srcChannel = istream.getChannel();
150         FileChannel destChannel = ostream.getChannel();
151         srcChannel.transferTo(0, srcChannel.size(), destChannel);
152         srcChannel.close();
153         destChannel.close();
154         istream.close();
155     }
156     
157     /**
158      * Copy file from the specified inputstream to the specified Writer
159      *
160      * @param istream Source input stream
161      * @param writer Writer to which the file will be written
162      *
163      */

164     public static void copyFileToWriter(InputStream istream, Writer writer)
165     throws IOException {
166         while(true){
167             int nextByte = istream.read();
168             if (nextByte==-1)
169                 break;
170             writer.write(nextByte);
171         }
172         istream.close();
173     }
174     
175     /**
176      * Copy lines containing search pattern from source file to destination file
177      *
178      * @param srcFileName Source filename
179      * @param dstFileName Destination filename
180      * @param searchPattern Search pattern
181      *
182      */

183     public static void copySearchPatternToFile(String JavaDoc srcFileName,
184             String JavaDoc dstFileName, String JavaDoc searchPattern)
185             throws FileNotFoundException, IOException {
186         BufferedReader inFile = new BufferedReader(new FileReader(srcFileName));
187         PrintWriter out = new PrintWriter
188                 (new BufferedWriter(new FileWriter(dstFileName)));
189         String JavaDoc fileLine;
190         while((fileLine = inFile.readLine()) != null)
191             if (fileLine.matches("(?i).*"+searchPattern+".*"))
192                 out.println(fileLine);
193         if (inFile != null)
194             inFile.close();
195         if (out != null)
196             out.close();
197     }
198     
199     /**
200      * Copy files from the specified source directory to destination directory
201      *
202      * @param srcDir Absolute path of the source directory to be copied
203      * @param dstDir Absolute path of the destination directory and dstDir
204      * should exist
205      *
206      */

207     public static void copyDir(String JavaDoc srcDir, String JavaDoc dstDir)
208     throws IOException {
209         copyDir(srcDir, dstDir, null, false);
210     }
211     
212     /**
213      * Copy files from the specified source directory to destination directory
214      *
215      * @param srcDir Absolute path of the source directory to be copied
216      * @param dstDir Absolute path of the destination directory and dstDir
217      * should exist
218      * @param subDir Boolean value specifies whether to copy files
219      * from subdirectory
220      *
221      */

222     public static void copyDir(String JavaDoc srcDir, String JavaDoc dstDir, boolean subDir)
223     throws IOException {
224         copyDir(srcDir, dstDir, null, subDir);
225     }
226     
227     /**
228      * Copy files from the specified source directory to destination directory
229      *
230      * @param srcDir Absolute path of the source directory to be copied
231      * @param dstDir Absolute path of the destination directory and dstDir should exist
232      * @param subDir Boolean value specifies whether to copy files from subdirectory
233      *
234      */

235     public static void copyDir(String JavaDoc srcDir, String JavaDoc dstDir,
236             FilenameFilter filter, boolean subDir)
237             throws IOException {
238         int numFiles = 0;
239         String JavaDoc [] strFiles = null;
240         
241         if (filter == null)
242             strFiles = (new File(srcDir)).list();
243         else
244             strFiles = (new File(srcDir)).list(filter);
245         
246         if (strFiles != null)
247             numFiles = strFiles.length;
248         
249         for (int i=0; i<numFiles; i++) {
250             String JavaDoc srcFile = srcDir+File.separator+strFiles[i];
251             String JavaDoc dstFile = dstDir+File.separator+strFiles[i];
252             if ((new File(srcFile)).isFile()) {
253                 copyFile(srcFile,dstFile);
254             } else if(subDir) {
255                 File dstSubDir = new File(dstFile);
256                 dstSubDir.mkdirs();
257                 copyDir(srcFile,dstFile,filter,subDir);
258             }
259         }
260     }
261     
262   /**
263      * Extracts the jar files in the given directory.<BR>
264      * Note: will not look recursively (in subdirs) for .jar files.
265      * @param dir Directory where .jar files has to be searched.
266      * @param dest Destination directory where files will be extracted.
267      */

268    public static void extractJarFiles(String JavaDoc dir, String JavaDoc dest){
269        try{
270            File aJarDir = new File(dir);
271            File files[] = aJarDir.listFiles();
272
273            FilenameFilter filter = getFilenameFilter(".jar");
274
275            for(File file : files)
276            {
277                //if(file.getName().toLowerCase().endsWith(".jar")){
278
if(filter.accept(aJarDir, file.getName())){
279                    String JavaDoc fileName = file.getName();
280                    //String dirName = fileName.substring(0, fileName.toLowerCase().indexOf(".jar"));
281
//File outputDir = new File(dest+ File.separator + dirName);
282
File outputDir = new File(dest);
283
284                    outputDir.mkdirs();
285
286
287                    unjar(file,"",outputDir.getAbsolutePath());
288
289                     file.delete();
290                }
291            }
292        }
293        catch(Exception JavaDoc e){
294             logger.log(Level.WARNING, e.getMessage(), e.fillInStackTrace());
295        }
296    }
297
298     public static FilenameFilter getFilenameFilter(final String JavaDoc extension){
299         FilenameFilter filter = new FilenameFilter() {
300             public boolean accept(File dir, String JavaDoc name) {
301                 boolean result = false;
302                 if(name !=null && extension !=null){
303                     result = name.toLowerCase().endsWith(extension.toLowerCase());
304                 }
305                 return result;
306             }
307         };
308         return filter;
309     }
310     /**
311      * Jar the contents of the specified directory including all
312      * subdirectories.
313      *
314      * @param jarFile Ouput JAR file
315      * @param dir Absoilute path of the directory to be JAR'd
316      *
317      */

318     public static void jarDirectory(File jarFile, String JavaDoc dir) {
319
320         try{
321             
322
323             BufferedInputStream origin = null;
324             File aJarDir = new File(dir);
325             File parent = jarFile.getParentFile();
326             
327             if(!parent.exists())
328                 parent.mkdirs();
329             
330             FileOutputStream dest = new FileOutputStream(jarFile);
331             JarOutputStream out = new JarOutputStream(new BufferedOutputStream(dest));
332             out.setMethod(JarOutputStream.DEFLATED);
333             byte data[] = new byte[BUFFER];
334             
335             List files = FileUtils.getFileListing( aJarDir, true );
336             
337             Iterator filesIter = files.iterator();
338             int length = dir.length() ;
339             //System.out.println(" Directory : " + dir + " : Length : " + length);
340

341             while( filesIter.hasNext() ){
342                 File f = (File)filesIter.next();
343                 String JavaDoc path = f.getPath();
344                 String JavaDoc relativePath = path.substring(length);
345                 if(relativePath.startsWith(""+File.separator))
346                     relativePath = path.substring(length +1);
347                     
348                 if (f.isDirectory())
349                     relativePath = relativePath + "/";
350
351                 //System.out.println(" Relative Path :" + relativePath);
352
JarEntry entry = new JarEntry(relativePath);
353                 out.putNextEntry(entry);
354                 
355                 if (!f.isDirectory()){
356                     FileInputStream fi = new FileInputStream(path);
357                     origin = new BufferedInputStream(fi, BUFFER);
358                     
359                     int count;
360                     while((count = origin.read(data, 0, BUFFER)) != -1) {
361                         out.write(data, 0, count);
362                     }
363                 }
364                 if(origin!=null)
365                     try{origin.close();}catch(Exception JavaDoc e){e.printStackTrace();}
366             }
367             if(out!=null)
368                 try{out.close();}catch(Exception JavaDoc e){e.printStackTrace();}
369         } catch (FileNotFoundException fnfEx){
370             fnfEx.printStackTrace();
371         } catch (IOException ioEx){
372             ioEx.printStackTrace();
373         }
374     }
375     
376     /**
377      * Jar the contents of the specified directory including all
378      * subdirectories.
379      *
380      * @param jarFile Ouput JAR file
381      * @param dir Absoilute path of the directory to be JAR'd
382      *
383      */

384     public static void zipDirectory(File jarFile, String JavaDoc dir) {
385         try{
386             BufferedInputStream origin = null;
387             File aJarDir = new File(dir);
388             FileOutputStream dest = new FileOutputStream(jarFile);
389             ZipOutputStream out = new ZipOutputStream(
390                     new BufferedOutputStream(dest));
391             out.setMethod(ZipOutputStream.DEFLATED);
392             byte data[] = new byte[BUFFER];
393             
394             List files = FileUtils.getFileListing( aJarDir, true );
395             
396             Iterator filesIter = files.iterator();
397             while( filesIter.hasNext() ){
398                 File f = (File)filesIter.next();
399                 String JavaDoc path = f.getPath();
400                 if (f.isDirectory())
401                     path = path + "/";
402                 
403                 ZipEntry entry = new ZipEntry(path);
404                 out.putNextEntry(entry);
405                 
406                 if (!f.isDirectory()){
407                     FileInputStream fi = new FileInputStream(path);
408                     origin = new BufferedInputStream(fi, BUFFER);
409                     
410                     int count;
411                     while((count = origin.read(data, 0, BUFFER)) != -1) {
412                         out.write(data, 0, count);
413                     }
414                 }
415                 if(origin!=null)
416                     try{origin.close();}catch(Exception JavaDoc e){e.printStackTrace();}
417             }
418             if(out!=null)
419                 try{out.close();}catch(Exception JavaDoc e){e.printStackTrace();}
420         } catch (FileNotFoundException fnfEx){
421             fnfEx.printStackTrace();
422         } catch (IOException ioEx){
423             ioEx.printStackTrace();
424         }
425     }
426     public static void unjar(File jarFile, String JavaDoc entryPath, String JavaDoc destDir) {
427         
428         final int BUFFER = 2048;
429         try {
430             BufferedOutputStream dest;
431             BufferedInputStream is;
432             byte data[] = new byte[BUFFER];
433             
434             if (entryPath==null)
435                 entryPath="";
436             
437             JarFile jarfile = new JarFile(jarFile);
438             Enumeration e = jarfile.entries();
439             
440             while(e.hasMoreElements()) { //going through each entries one by one
441
JarEntry entry = (JarEntry) e.nextElement();
442                 is = new BufferedInputStream(jarfile.getInputStream(entry));
443                 
444                 String JavaDoc path = entry.getName();
445                 if (path.startsWith(entryPath)) {
446                     int start = path.lastIndexOf("/");
447                     String JavaDoc basis = null;
448                     if(start != -1) {
449                         basis = path.substring(0, start);
450                     }
451                     String JavaDoc filename = path.substring(start + 1);
452                     File tmpPath = new File(destDir);
453                     if(basis != null && basis.length() != 0){
454                         tmpPath = new File(tmpPath, basis);
455                         tmpPath.mkdirs();
456                     }
457                     
458                     if(filename != null && filename.length() != 0){
459                         File destfile = new File(tmpPath, filename);
460                         FileOutputStream fos = new FileOutputStream(destfile);
461                         dest = new BufferedOutputStream(fos, BUFFER);
462                         
463                         int count;
464                         while ((count = is.read(data, 0, BUFFER))!= -1) {
465                             dest.write(data, 0, count);
466                         }
467                         dest.flush();
468                         dest.close();
469                         is.close();
470                     }
471                 }
472             }
473         } catch(Exception JavaDoc e) {
474             e.printStackTrace();
475         }
476     }
477     
478     /**
479      * Recursively walk a directory tree and return a List of all
480      * Files found; the List is sorted using File.compareTo.
481      *
482      * @param aStartingDir is a valid directory, which can be read.
483      */

484     static public List getFileListing( File aStartingDir , boolean recurse) throws FileNotFoundException{
485         validateDirectory(aStartingDir);
486         File[] filesAndDirs = aStartingDir.listFiles();
487         List filesDirs = Arrays.asList(filesAndDirs);
488         
489         if (!recurse) {
490             Collections.sort(filesDirs);
491             return filesDirs;
492         }
493         
494         Iterator filesIter = filesDirs.iterator();
495         List result = new ArrayList();
496         File file = null;
497         while ( filesIter.hasNext() ) {
498             file = (File)filesIter.next();
499             result.add(file); //always add, even if directory
500
if (recurse && !file.isFile()) {
501                 //must be a directory
502
//recursive call!
503
List deeperList = getFileListing(file, true);
504                 result.addAll(deeperList);
505             }
506             
507         }
508         Collections.sort(result);
509         return result;
510     }
511     
512     /**
513      * Recursively walk a directory tree and return a List of all
514      * Files matching the name pattern; the List is sorted using File.compareTo.
515      *
516      * @param aStartingDir is a valid directory, which can be read.
517      * @boolean recurse
518      * @param nameFilter pattern for name
519      * @param comparator sorts files
520      */

521     static public List getFileListing(File aStartingDir, boolean recurse,
522             FilenameFilter nameFilter, Comparator comparator)
523             throws FileNotFoundException {
524         
525         validateDirectory(aStartingDir);
526         
527         File[] filesAndDirs = aStartingDir.listFiles(nameFilter);
528         List filesDirs = Arrays.asList(filesAndDirs);
529         
530         if (!recurse) {
531             Collections.sort(filesDirs, comparator);
532             return filesDirs;
533         }
534         
535         Iterator filesIter = filesDirs.iterator();
536         List result = new ArrayList();
537         File file = null;
538         while ( filesIter.hasNext() ) {
539             file = (File)filesIter.next();
540             result.add(file); //always add, even if directory
541
if (recurse && !file.isFile()) {
542                 //must be a directory
543
//recursive call!
544
List deeperList = getFileListing(file,true);
545                 result.addAll(deeperList);
546             }
547             
548         }
549         Collections.sort(result, comparator);
550         return result;
551     }
552     
553     /**
554      * Directory is valid if it exists, does not represent a file, and can be read.
555      */

556     static private void validateDirectory(File aDirectory) throws FileNotFoundException {
557         if (aDirectory == null) {
558             throw new IllegalArgumentException JavaDoc("Directory should not be null.");
559         }
560         if (!aDirectory.exists()) {
561             throw new FileNotFoundException("Directory does not exist: " + aDirectory);
562         }
563         if (!aDirectory.isDirectory()) {
564             throw new IllegalArgumentException JavaDoc("Is not a directory: " + aDirectory);
565         }
566         if (!aDirectory.canRead()) {
567             throw new IllegalArgumentException JavaDoc("Directory cannot be read: " + aDirectory);
568         }
569     }
570     
571     
572     
573     /**
574      * Get the name of the file or directory from an absolute path
575      * @param absPath Absolute path
576      * @return Name of the directory or file
577      */

578     public static String JavaDoc getFileName(String JavaDoc absPath) {
579         File file = new File(absPath);
580         return file.getName();
581     }
582     
583     public static void deleteFile(String JavaDoc fileName){
584         deleteFile(new File(fileName));
585     }
586     
587     public static void deleteFile(File file){
588         if (file != null) {
589             if(file.isDirectory()){
590                 File[] files = file.listFiles();
591                 int size = files.length;
592                 for(int i =0; i < size; i++){
593                     deleteFile(files[i]);
594                 }
595             }
596             file.delete();
597         }
598     }
599     
600     public static void moveFile(String JavaDoc sourceFile, String JavaDoc destFile)
601     throws IOException {
602         copyFile(sourceFile, destFile);
603         new File(sourceFile).delete();
604     }
605 }
606
Popular Tags