View Javadoc

1   /*
2    * ModeShape (http://www.modeshape.org)
3    * See the COPYRIGHT.txt file distributed with this work for information
4    * regarding copyright ownership.  Some portions may be licensed
5    * to Red Hat, Inc. under one or more contributor license agreements.
6    * See the AUTHORS.txt file in the distribution for a full listing of 
7    * individual contributors. 
8    *
9    * ModeShape is free software. Unless otherwise indicated, all code in ModeShape
10   * is licensed to you under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation; either version 2.1 of
12   * the License, or (at your option) any later version.
13   *
14   * ModeShape is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17   * Lesser General Public License for more details.
18   *
19   * You should have received a copy of the GNU Lesser General Public
20   * License along with this software; if not, write to the Free
21   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
22   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
23   */
24  
25  package org.modeshape.common.util;
26  
27  import java.io.BufferedInputStream;
28  import java.io.BufferedOutputStream;
29  import java.io.File;
30  import java.io.FileInputStream;
31  import java.io.FileOutputStream;
32  import java.io.FilenameFilter;
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.OutputStream;
36  import java.net.MalformedURLException;
37  import java.net.URL;
38  import net.jcip.annotations.Immutable;
39  
40  /**
41   * A set of utilities for working with files and directories.
42   */
43  @Immutable
44  public class FileUtil {
45  
46      private static FilenameFilter ACCEPT_ALL = new FilenameFilter() {
47  
48          public boolean accept( File dir,
49                                 String name ) {
50              return true;
51          }
52      };
53  
54      /**
55       * Delete the file or directory at the supplied path. This method works on a directory that is not empty, unlike the
56       * {@link File#delete()} method.
57       * 
58       * @param path the path to the file or directory that is to be deleted
59       * @return true if the file or directory at the supplied path existed and was successfully deleted, or false otherwise
60       */
61      public static boolean delete( String path ) {
62          if (path == null || path.trim().length() == 0) return false;
63          return delete(new File(path));
64      }
65  
66      /**
67       * Delete the file or directory given by the supplied reference. This method works on a directory that is not empty, unlike
68       * the {@link File#delete()} method.
69       * 
70       * @param fileOrDirectory the reference to the Java File object that is to be deleted
71       * @return true if the supplied file or directory existed and was successfully deleted, or false otherwise
72       */
73      public static boolean delete( File fileOrDirectory ) {
74          if (fileOrDirectory == null) return false;
75          if (!fileOrDirectory.exists()) return false;
76  
77          // The file/directory exists, so if a directory delete all of the contents ...
78          if (fileOrDirectory.isDirectory()) {
79              for (File childFile : fileOrDirectory.listFiles()) {
80                  delete(childFile); // recursive call (good enough for now until we need something better)
81              }
82              // Now an empty directory ...
83          }
84          // Whether this is a file or empty directory, just delete it ...
85          return fileOrDirectory.delete();
86      }
87  
88      /**
89       * Copy the source file system structure into the supplied target location. If the source is a file, the destination will be
90       * created as a file; if the source is a directory, the destination will be created as a directory.
91       * 
92       * @param sourceFileOrDirectory the file or directory whose contents are to be copied into the target location
93       * @param destinationFileOrDirectory the location where the copy is to be placed; does not need to exist, but if it does its
94       *        type must match that of <code>src</code>
95       * @return the number of files (not directories) that were copied
96       * @throws IllegalArgumentException if the <code>src</code> or <code>dest</code> references are null
97       * @throws IOException
98       */
99      public static int copy( File sourceFileOrDirectory,
100                             File destinationFileOrDirectory ) throws IOException {
101         return copy(sourceFileOrDirectory, destinationFileOrDirectory, null);
102     }
103 
104     /**
105      * Copy the source file system structure into the supplied target location. If the source is a file, the destination will be
106      * created as a file; if the source is a directory, the destination will be created as a directory.
107      * 
108      * @param sourceFileOrDirectory the file or directory whose contents are to be copied into the target location
109      * @param destinationFileOrDirectory the location where the copy is to be placed; does not need to exist, but if it does its
110      *        type must match that of <code>src</code>
111      * @param exclusionFilter a filter that matches files or folders that should _not_ be copied; null indicates that all files
112      *        and folders should be copied
113      * @return the number of files (not directories) that were copied
114      * @throws IllegalArgumentException if the <code>src</code> or <code>dest</code> references are null
115      * @throws IOException
116      */
117     public static int copy( File sourceFileOrDirectory,
118                             File destinationFileOrDirectory,
119                             FilenameFilter exclusionFilter ) throws IOException {
120         if (exclusionFilter == null) exclusionFilter = ACCEPT_ALL;
121         int numberOfFilesCopied = 0;
122         if (sourceFileOrDirectory.isDirectory()) {
123             destinationFileOrDirectory.mkdirs();
124             String list[] = sourceFileOrDirectory.list(exclusionFilter);
125 
126             for (int i = 0; i < list.length; i++) {
127                 String dest1 = destinationFileOrDirectory.getPath() + File.separator + list[i];
128                 String src1 = sourceFileOrDirectory.getPath() + File.separator + list[i];
129 
130                 numberOfFilesCopied += copy(new File(src1), new File(dest1), exclusionFilter);
131             }
132         } else {
133             InputStream fin = new FileInputStream(sourceFileOrDirectory);
134             fin = new BufferedInputStream(fin);
135             try {
136                 OutputStream fout = new FileOutputStream(destinationFileOrDirectory);
137                 fout = new BufferedOutputStream(fout);
138                 try {
139                     int c;
140                     while ((c = fin.read()) >= 0) {
141                         fout.write(c);
142                     }
143                 } finally {
144                     fout.close();
145                 }
146             } finally {
147                 fin.close();
148             }
149             numberOfFilesCopied++;
150         }
151         return numberOfFilesCopied;
152     }
153 
154     /**
155      * Utility to convert {@link File} to {@link URL}.
156      * 
157      * @param filePath the path of the file
158      * @return the {@link URL} representation of the file.
159      * @throws MalformedURLException
160      * @throws IllegalArgumentException if the file path is null, empty or blank
161      */
162     public static URL convertFileToURL( String filePath ) throws MalformedURLException {
163         CheckArg.isNotEmpty(filePath, "filePath");
164         File file = new File(filePath.trim());
165         return file.toURI().toURL();
166     }
167 
168 }