View Javadoc

1   package net.sf.mmapps.commons.util;
2   
3   import java.io.*;
4   import java.util.ArrayList;
5   import java.util.Comparator;
6   import java.util.Iterator;
7   import java.util.List;
8   import java.util.regex.Matcher;
9   import java.util.regex.Pattern;
10  
11  public class FileUtil {
12     
13     public static String readString(String name) {
14        return readString(name, 0, true);
15     }
16     
17     public static String readString(String name, int skiplines, boolean keepLines) {
18        StringBuffer read = new StringBuffer();
19        
20        File f = new File(name);
21        BufferedReader br = null;
22  
23        try {
24            br = new BufferedReader(new FileReader(f));
25  
26            for (int i = 0; (i < skiplines) && (br.readLine() != null); i++) {
27                //skip lines
28            }
29  
30            String line = null;
31  
32            while ((line = br.readLine()) != null) {
33                read.append(line);
34                if (keepLines) {
35                   read.append("\n");
36                }
37            }
38        } catch (FileNotFoundException e) {
39            System.out.println("File not found " + f.toString());
40        } catch (IOException e) {
41            System.out.println("IOerror: " + e.getMessage());
42        } finally {
43            if (br != null) {
44                try {
45                    br.close();
46                } catch (IOException e1) {
47                    // do nothing when close fails
48                }
49            }
50        }
51        return read.toString();
52    }
53  
54     /***
55      * Move files from String origin to String destination.
56      * @param origin original folder
57      * @param destination destination folder
58      * @param filter move only matching files
59      * @throws IOException when an error occurs
60      */
61     public static void moveFolderContent(String origin, String destination, FileFilter filter) throws IOException {
62       File originFolder = new File(origin);
63       File destinationFolder = new File(destination);
64  
65       if (originFolder.isDirectory()) {
66          File[] filesInThisDirectory = originFolder.listFiles(filter);
67          // create the destination folder if necessary...
68          if (filesInThisDirectory.length > 0 && !destinationFolder.exists()) {
69             destinationFolder.mkdirs();
70          }
71          for (int i = 0; i < filesInThisDirectory.length; i++) {
72             String originFile = filesInThisDirectory[i].getPath();
73             String originFileName = filesInThisDirectory[i].getName();
74             String destinationFile = destination + File.separator + originFileName;
75             File fileInput = new File(originFile);
76             File fileOutput = new File(destinationFile);
77             if (fileOutput.exists()) {
78                fileOutput.delete();
79             }
80             if (fileInput.renameTo(fileOutput)) {
81                System.out.println("MOVED " + originFile);
82             }
83             else {
84                System.out.println("MOVE FAILED " + originFile);
85             }
86          }
87          
88          File[] dirsInThisDirectory = originFolder.listFiles(new DirectoryOnlyFilter());
89          for (int i = 0; i < dirsInThisDirectory.length; i++) {
90             String originFile = dirsInThisDirectory[i].getPath();
91             String originFileName = dirsInThisDirectory[i].getName();
92             String destinationFile = destination + File.separator + originFileName;
93             moveFolderContent(originFile, destinationFile, filter);
94          }
95       }
96    }
97  
98    /***
99      * Copy files from String origin to String destination.
100     * @param origin original folder
101     * @param destination destination folder
102     * @param filter move only matching files
103     * @throws IOException when an error occurs
104     */
105    public static void copyFolderContent(String origin, String destination, FileFilter filter) throws IOException {
106       File originFolder = new File(origin);
107       File destinationFolder = new File(destination);
108 
109       if (originFolder.isDirectory()) {
110          File[] filesInThisDirectory = originFolder.listFiles(filter);
111          // create the destination folder if necessary...
112          if (filesInThisDirectory.length > 0 && !destinationFolder.exists()) {
113             destinationFolder.mkdirs();
114          }
115          for (int i = 0; i < filesInThisDirectory.length; i++) {
116             String originFile = filesInThisDirectory[i].getPath();
117             String originFileName = filesInThisDirectory[i].getName();
118             String destinationFile = destination + File.separator + originFileName;
119             if (filesInThisDirectory[i].isFile()) {
120                writeFileInFile(originFile, destinationFile);
121             }
122          }
123          
124          File[] dirsInThisDirectory = originFolder.listFiles(new DirectoryOnlyFilter());
125          for (int i = 0; i < dirsInThisDirectory.length; i++) {
126             String originFile = dirsInThisDirectory[i].getPath();
127             String originFileName = dirsInThisDirectory[i].getName();
128             String destinationFile = destination + File.separator + originFileName;
129             copyFolderContent(originFile, destinationFile, filter);
130          }
131       }
132    }
133 
134    /***
135      * Write a string in a file.
136      * 
137      * @param fileName File name.
138      * @param output String output.
139      */
140   public static void writeStringInFile(String fileName, String output) {
141      // try to write the file...
142      try {
143         File fileObject = new File(fileName);
144         File folder = fileObject.getParentFile();
145         if (!folder.exists()) {
146             if (!folder.mkdirs()) {
147                 System.out.println("DIR CREATION FAILED " + fileName);
148             }
149         }
150         FileWriter fileWriter = new FileWriter(fileObject);
151         fileWriter.write(output);
152         fileWriter.close();
153      }
154      catch (IOException ioe) {
155          System.out.println("WRITE FAILED " + fileName);
156      }
157   }
158   
159     public static void writeFileInFile(String fileName, String destinationFile)
160             throws IOException {
161         InputStream fileInput = null;
162         try {
163             File fileObject = new File(fileName);
164             File folder = fileObject.getParentFile();
165             if (!folder.exists()) {
166                 if (!folder.mkdirs()) {
167                     System.out.println("DIR CREATION FAILED " + fileName);
168                 }
169             }
170             fileInput = getInputStream(fileName);
171             writeStreamInFile(destinationFile, fileInput);
172         }
173         catch (IOException ioe) {
174             System.out.println("COPY FAILED " + fileName);
175         }
176         finally {
177             if (fileInput != null) {
178                 fileInput.close();
179             }
180         }
181     }
182 
183     public static InputStream getInputStream(String fileName) throws FileNotFoundException {
184         return new FileInputStream(fileName);
185     }
186 
187    public static void writeBytesInFile(String fileName, byte[] bytes) throws IOException {
188        InputStream input = null;
189        try {
190            File fileObject = new File(fileName);
191            File folder = fileObject.getParentFile();
192            if (!folder.exists()) {
193                if (!folder.mkdirs()) {
194                    System.out.println("DIR CREATION FAILED " + fileName);
195                }
196            }
197            input = new ByteArrayInputStream(bytes);
198            writeStreamInFile(fileName, input);
199        }
200        catch(IOException ioe) {
201           System.out.println("COPY FAILED " + fileName);
202        }
203        finally {
204           if (input != null) {
205              input.close();
206           }
207        }
208     }
209    
210     public static void writeStreamInFile(String fileName, InputStream input)
211             throws IOException {
212         FileOutputStream fileOutput = null;
213         try {
214             File fileObject = new File(fileName);
215             File folder = fileObject.getParentFile();
216             if (!folder.exists()) {
217                 if (!folder.mkdirs()) {
218                     System.out.println("DIR CREATION FAILED " + fileName);
219                 }
220             }
221             fileOutput = new FileOutputStream(fileName);
222             copyStream(input, fileOutput);
223         }
224         catch (IOException ioe) {
225             System.out.println("COPY FAILED " + fileName);
226         }
227         finally {
228             if (fileOutput != null) {
229                 fileOutput.close();
230             }
231         }
232     }
233 
234    /***
235     * Copy an InputStream to an OutputStream
236     * @param inputStream input
237     * @param outputStream output
238     * @throws IOException when an error occurs
239     */
240    public static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
241       int bufferRead;
242       int bufferSize = 65536;
243       byte[] writeBuffer = new byte[bufferSize];
244 
245       BufferedInputStream bufInStream = new BufferedInputStream(inputStream, bufferSize);
246       BufferedOutputStream bufOutStream = new BufferedOutputStream(outputStream, bufferSize);
247       while ((bufferRead = bufInStream.read(writeBuffer)) != -1) {
248          bufOutStream.write(writeBuffer, 0, bufferRead);
249       }
250       bufOutStream.flush();
251       bufOutStream.close();
252    }
253 
254    public static boolean checkFileExists(String fileName) {
255       if (fileName != null) {
256          File fileObject = new File(fileName);
257          return fileObject.exists();
258       }
259       return false;
260    }
261 
262    /***
263 	 * check if a file or directory exists on disk. The check is case sensitive
264 	 * 
265 	 * @param path the absolute path
266 	 * @return boolean true if comparison is success
267 	 */
268    public static boolean checkFileNameCaseSensitive(String path) {
269       File tmpFile = new File(path);
270       if (tmpFile != null && (tmpFile.isFile() || tmpFile.isDirectory())) {
271          String name = tmpFile.getName();
272          if (tmpFile.getParentFile() != null) {
273             File[] files = tmpFile.getParentFile().listFiles();
274             int nbFiles = files.length;
275             for (int i = 0; i < nbFiles; i++) {
276                if (files[i].getName().equals(name)) {
277                   return true;
278                }
279             }
280          }
281       }
282       return false;
283    }
284 
285    /***
286 	 * delete a file or directory (and all its content)
287 	 * 
288 	 * @param f the abstract file object
289      * @return completed without errors
290 	 */
291    public static boolean deleteFile(File f) {
292       return deleteFile(f, false);
293    }
294 
295    /***
296 	 * delete a file or directory ( and all its contains )
297 	 * 
298 	 * @param f the abstract file object
299 	 * @param contentOnly id true, delete only the folder content
300      * @return completed without errors
301 	 */
302    public static boolean deleteFile(File f, boolean contentOnly) {
303       if (f == null) {
304          return false;
305       }
306 
307       if (f.isDirectory()) {
308          File[] files = f.listFiles();
309 
310          for (int i = 0; i < files.length; i++) {
311             if (files[i].isFile()) {
312                files[i].delete();
313             }
314             else {
315                deleteFile(files[i], false);
316             }
317          }
318          if (!contentOnly) {
319             return f.delete();
320          }
321       }
322       else {
323          return f.delete();
324       }
325       return true;
326    }
327 
328    /***
329     * Return the file name but without the extension
330     * 
331     * @param filename the complete file name with extension
332     * @param ext the extension to remove @return(String) the filename
333     *           without a gived extension
334     * @return filename without extension
335     */
336    public static String removeFileExtension(String filename, String ext) {
337       String name = filename.toLowerCase();
338       if (name.endsWith(ext.toLowerCase())) {
339          return (filename.substring(0, name.lastIndexOf(ext.toLowerCase())));
340       }
341       return filename;
342    }
343    
344    /***
345     * Get the parent of a specific child folder
346     * @param child Child whose parent is to be retrieved
347     * @return Parent folder of the specified child.
348     */
349    public File getParent(File child) {
350        return child.getParentFile();
351    }
352    
353    /***
354     * Get all the child files (i.e. no directories) for a given
355     * relative path.
356     * @param path Path of files to retrieve.
357     * @return Returns an array of child File objects.
358     */
359    public File[] getChildFiles(String path) {
360        File dir = getFileFromPath(path);
361        return dir.listFiles(new FileOnlyFilter());
362    }
363    
364    /***
365     * Get the path of a directory or file relative to the root.
366     * @param file File whose path is to be retrieved.
367     * @param urlEncode If set to true, the returned path will be URL encoded.
368     * @return Returns the path of the specified file relative to the
369     *     repository root.
370     */
371    public String getPathFromFile(File file, boolean urlEncode) {
372        int start = 0;
373        String path = file.getPath();
374        if (path.length() > start) {
375            path = path.substring(start);
376            path = path.replace('//', '/') + "/";
377        } else {
378            path = "";
379        }
380        if (urlEncode) {
381             try {
382                return java.net.URLEncoder.encode(path, "UTF-8");
383             } catch (UnsupportedEncodingException e) {
384                return path;
385             }
386        }
387        return path;
388    }
389 
390    /***
391     * Given a path relative to the staging root, fetch the file.
392     * @param path Path of file to retrieve.
393     * @return Retuns the File for the given path in the staging repository.
394     */
395    public File getFileFromPath(String path) {
396        if (path == null) {
397            path = "";
398        }
399        return new File(path);
400    }
401    
402    public static class DirectoryOnlyFilter implements FileFilter {
403       public boolean accept(File file) {
404          return file.isDirectory();
405       }
406    }
407 
408    public static class FileOnlyFilter implements FileFilter {
409       public boolean accept(File file) {
410          return !file.isDirectory();
411       }
412    }
413    
414    /***
415     * The directory filter class is used to filter files in a directory
416     * based on whether the child itself is a directory or not.
417     */
418    public static class IgnoreFilter implements FileFilter {
419 
420        private List<Pattern> ignores = new ArrayList<Pattern>() ;
421 
422        /***
423         * Constructor for a directory filter
424         * @param ignores list of names to ignore
425         */
426        public IgnoreFilter(List ignores) {
427           for (Iterator iter = ignores.iterator(); iter.hasNext();) {
428             String element = (String) iter.next();
429             Pattern pattern = Pattern.compile(element);
430             this.ignores.add(pattern);
431          }
432        }
433 
434        /***
435         * Determine if the file meets the filter requirements.
436         * @return Returns true if the file is accepted, otherwise
437         *     returns false.
438         */
439        public boolean accept(File file) {
440           for (int i = 0; i < ignores.size(); i++) {
441              Pattern pattern = ignores.get(i);
442              Matcher m = pattern.matcher(file.getName());
443              if (m.matches()) {
444                 return false;
445              }
446           }
447           return true;
448        }
449    }
450    
451    static class LastModifiedComparator implements Comparator {
452 
453       /***
454        * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
455        */
456       public int compare(Object arg0, Object arg1) {
457          if (arg0 != null && arg1 != null && 
458              arg0 instanceof File && arg1 instanceof File) {
459             File f1 = (File) arg0;
460             File f2 = (File) arg1;
461             return (int)((f1.lastModified()/1000) - (f2.lastModified()/1000));
462          }
463          return 0;
464       }
465     }
466 }