1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.util;
24  
25  import com.liferay.portal.kernel.util.ByteArrayMaker;
26  import com.liferay.portal.kernel.util.StringPool;
27  import com.liferay.portal.kernel.util.StringUtil;
28  import com.liferay.portal.kernel.util.Validator;
29  
30  import java.io.BufferedInputStream;
31  import java.io.BufferedReader;
32  import java.io.BufferedWriter;
33  import java.io.File;
34  import java.io.FileInputStream;
35  import java.io.FileOutputStream;
36  import java.io.FileReader;
37  import java.io.FileWriter;
38  import java.io.IOException;
39  import java.io.InputStream;
40  import java.io.Reader;
41  
42  import java.nio.channels.FileChannel;
43  
44  import java.util.ArrayList;
45  import java.util.Arrays;
46  import java.util.List;
47  import java.util.Properties;
48  
49  import org.apache.commons.logging.Log;
50  import org.apache.commons.logging.LogFactory;
51  
52  /**
53   * <a href="FileUtil.java.html"><b><i>View Source</i></b></a>
54   *
55   * @author Brian Wing Shun Chan
56   * @author Alexander Chow
57   *
58   */
59  public class FileUtil {
60  
61      public static final String ENCODING = GetterUtil.getString(
62          SystemProperties.get("file.encoding"), "UTF-8");
63  
64      public static void append(String fileName, String s) throws IOException {
65          append(new File(fileName), s);
66      }
67  
68      public static void append(String pathName, String fileName, String s)
69          throws IOException {
70  
71          append(new File(pathName, fileName), s);
72      }
73  
74      public static void append(File file, String s) throws IOException {
75          if (file.getParent() != null) {
76              mkdirs(file.getParent());
77          }
78  
79          BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
80  
81          bw.write(s);
82  
83          bw.close();
84      }
85  
86      public static void copyDirectory(
87          String sourceDirName, String destinationDirName) {
88  
89          copyDirectory(new File(sourceDirName), new File(destinationDirName));
90      }
91  
92      public static void copyDirectory(File source, File destination) {
93          if (source.exists() && source.isDirectory()) {
94              if (!destination.exists()) {
95                  destination.mkdirs();
96              }
97  
98              File[] fileArray = source.listFiles();
99  
100             for (int i = 0; i < fileArray.length; i++) {
101                 if (fileArray[i].isDirectory()) {
102                     copyDirectory(
103                         fileArray[i],
104                         new File(destination.getPath() + File.separator
105                             + fileArray[i].getName()));
106                 }
107                 else {
108                     copyFile(
109                         fileArray[i],
110                         new File(destination.getPath() + File.separator
111                             + fileArray[i].getName()));
112                 }
113             }
114         }
115     }
116 
117     public static void copyFile(String source, String destination) {
118         copyFile(source, destination, false);
119     }
120 
121     public static void copyFile(
122         String source, String destination, boolean lazy) {
123 
124         copyFile(new File(source), new File(destination), lazy);
125     }
126 
127     public static void copyFile(File source, File destination) {
128         copyFile(source, destination, false);
129     }
130 
131     public static void copyFile(File source, File destination, boolean lazy) {
132         if (!source.exists()) {
133             return;
134         }
135 
136         if (lazy) {
137             String oldContent = null;
138 
139             try {
140                 oldContent = read(source);
141             }
142             catch (Exception e) {
143                 return;
144             }
145 
146             String newContent = null;
147 
148             try {
149                 newContent = read(destination);
150             }
151             catch (Exception e) {
152             }
153 
154             if (oldContent == null || !oldContent.equals(newContent)) {
155                 copyFile(source, destination, false);
156             }
157         }
158         else {
159             if ((destination.getParentFile() != null) &&
160                 (!destination.getParentFile().exists())) {
161 
162                 destination.getParentFile().mkdirs();
163             }
164 
165             try {
166                 FileChannel srcChannel =
167                     new FileInputStream(source).getChannel();
168                 FileChannel dstChannel =
169                     new FileOutputStream(destination).getChannel();
170 
171                 dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
172 
173                 srcChannel.close();
174                 dstChannel.close();
175             }
176             catch (IOException ioe) {
177                 _log.error(ioe.getMessage());
178             }
179         }
180     }
181 
182     public static boolean delete(String file) {
183         return delete(new File(file));
184     }
185 
186     public static boolean delete(File file) {
187         if (file.exists()) {
188             return file.delete();
189         }
190         else {
191             return false;
192         }
193     }
194 
195     public static void deltree(String directory) {
196         deltree(new File(directory));
197     }
198 
199     public static void deltree(File directory) {
200         if (directory.exists() && directory.isDirectory()) {
201             File[] fileArray = directory.listFiles();
202 
203             for (int i = 0; i < fileArray.length; i++) {
204                 if (fileArray[i].isDirectory()) {
205                     deltree(fileArray[i]);
206                 }
207                 else {
208                     fileArray[i].delete();
209                 }
210             }
211 
212             directory.delete();
213         }
214     }
215 
216     public static boolean exists(String fileName) {
217         return exists(new File(fileName));
218     }
219 
220     public static boolean exists(File file) {
221         return file.exists();
222     }
223 
224     public static String getAbsolutePath(File file) {
225         return StringUtil.replace(
226             file.getAbsolutePath(), StringPool.BACK_SLASH, StringPool.SLASH);
227     }
228 
229     public static byte[] getBytes(File file) throws IOException {
230         if ((file == null) || !file.exists()) {
231             return null;
232         }
233 
234         FileInputStream in = new FileInputStream(file);
235 
236         byte[] bytes = getBytes(in, (int)file.length());
237 
238         in.close();
239 
240         return bytes;
241     }
242 
243     public static byte[] getBytes(InputStream in) throws IOException {
244         return getBytes(in, -1);
245     }
246 
247     public static byte[] getBytes(InputStream in, int bufferSize)
248         throws IOException {
249 
250         ByteArrayMaker out = null;
251 
252         if (bufferSize <= 0) {
253             out = new ByteArrayMaker();
254         }
255         else {
256             out = new ByteArrayMaker(bufferSize);
257         }
258 
259         boolean createBuffered = false;
260 
261         try {
262             if (!(in instanceof BufferedInputStream)) {
263                 in = new BufferedInputStream(in);
264 
265                 createBuffered = true;
266             }
267 
268             int c = in.read();
269 
270             while (c != -1) {
271                 out.write(c);
272 
273                 c = in.read();
274             }
275         }
276         finally {
277             if (createBuffered) {
278                 in.close();
279             }
280         }
281 
282         out.close();
283 
284         return out.toByteArray();
285     }
286 
287     public static String getExtension(String fileName) {
288         if (fileName == null) {
289             return null;
290         }
291 
292         int pos = fileName.lastIndexOf(StringPool.PERIOD);
293 
294         if (pos != -1) {
295             return fileName.substring(pos + 1, fileName.length()).toLowerCase();
296         }
297         else {
298             return null;
299         }
300     }
301 
302     public static String getPath(String fullFileName) {
303         int pos = fullFileName.lastIndexOf(StringPool.SLASH);
304 
305         if (pos == -1) {
306             pos = fullFileName.lastIndexOf(StringPool.BACK_SLASH);
307         }
308 
309         String shortFileName = fullFileName.substring(0, pos);
310 
311         if (Validator.isNull(shortFileName)) {
312             return StringPool.SLASH;
313         }
314 
315         return shortFileName;
316     }
317 
318     public static String getShortFileName(String fullFileName) {
319         int pos = fullFileName.lastIndexOf(StringPool.SLASH);
320 
321         if (pos == -1) {
322             pos = fullFileName.lastIndexOf(StringPool.BACK_SLASH);
323         }
324 
325         String shortFileName =
326             fullFileName.substring(pos + 1, fullFileName.length());
327 
328         return shortFileName;
329     }
330 
331     public static String[] listDirs(String fileName) throws IOException {
332         return listDirs(new File(fileName));
333     }
334 
335     public static String[] listDirs(File file) throws IOException {
336         List dirs = new ArrayList();
337 
338         File[] fileArray = file.listFiles();
339 
340         for (int i = 0; i < fileArray.length; i++) {
341             if (fileArray[i].isDirectory()) {
342                 dirs.add(fileArray[i].getName());
343             }
344         }
345 
346         return (String[])dirs.toArray(new String[0]);
347     }
348 
349     public static String[] listFiles(String fileName) throws IOException {
350         if (Validator.isNull(fileName)) {
351             return new String[0];
352         }
353 
354         return listFiles(new File(fileName));
355     }
356 
357     public static String[] listFiles(File file) throws IOException {
358         List files = new ArrayList();
359 
360         File[] fileArray = file.listFiles();
361 
362         for (int i = 0; (fileArray != null) && (i < fileArray.length); i++) {
363             if (fileArray[i].isFile()) {
364                 files.add(fileArray[i].getName());
365             }
366         }
367 
368         return (String[])files.toArray(new String[0]);
369     }
370 
371     public static void mkdirs(String pathName) {
372         File file = new File(pathName);
373 
374         file.mkdirs();
375     }
376 
377     public static boolean move(
378         String sourceFileName, String destinationFileName) {
379 
380         return move(new File(sourceFileName), new File(destinationFileName));
381     }
382 
383     public static boolean move(File source, File destination) {
384         if (!source.exists()) {
385             return false;
386         }
387 
388         destination.delete();
389 
390         return source.renameTo(destination);
391     }
392 
393     public static String read(String fileName) throws IOException {
394         return read(new File(fileName));
395     }
396 
397     public static String read(File file) throws IOException {
398         return read(file, false);
399     }
400 
401     public static String read(File file, boolean raw) throws IOException {
402         return read(file, ENCODING, raw);
403     }
404 
405     public static String read(File file, String encoding, boolean raw)
406         throws IOException {
407 
408         FileInputStream fis = new FileInputStream(file);
409 
410         byte[] bytes = new byte[fis.available()];
411 
412         fis.read(bytes);
413 
414         fis.close();
415 
416         String s = new String(bytes, encoding);
417 
418         if (raw) {
419             return s;
420         }
421         else {
422             return StringUtil.replace(
423                 s, StringPool.RETURN_NEW_LINE, StringPool.NEW_LINE);
424         }
425     }
426 
427     public static File[] sortFiles(File[] files) {
428         if (files == null) {
429             return null;
430         }
431 
432         Arrays.sort(files, new FileComparator());
433 
434         List directoryList = new ArrayList();
435         List fileList = new ArrayList();
436 
437         for (int i = 0; i < files.length; i++) {
438             if (files[i].isDirectory()) {
439                 directoryList.add(files[i]);
440             }
441             else {
442                 fileList.add(files[i]);
443             }
444         }
445 
446         directoryList.addAll(fileList);
447 
448         return (File[])directoryList.toArray(new File[0]);
449     }
450 
451     public static String replaceSeparator(String fileName) {
452         return StringUtil.replace(
453             fileName, StringPool.BACK_SLASH, StringPool.SLASH);
454     }
455 
456     public static List toList(Reader reader) {
457         List list = new ArrayList();
458 
459         try {
460             BufferedReader br = new BufferedReader(reader);
461 
462             String line = null;
463 
464             while ((line = br.readLine()) != null) {
465                 list.add(line);
466             }
467 
468             br.close();
469         }
470         catch (IOException ioe) {
471         }
472 
473         return list;
474     }
475 
476     public static List toList(String fileName) {
477         try {
478             return toList(new FileReader(fileName));
479         }
480         catch (IOException ioe) {
481             return new ArrayList();
482         }
483     }
484 
485     public static Properties toProperties(FileInputStream fis) {
486         Properties props = new Properties();
487 
488         try {
489             props.load(fis);
490         }
491         catch (IOException ioe) {
492         }
493 
494         return props;
495     }
496 
497     public static Properties toProperties(String fileName) {
498         try {
499             return toProperties(new FileInputStream(fileName));
500         }
501         catch (IOException ioe) {
502             return new Properties();
503         }
504     }
505 
506     public static void write(String fileName, String s) throws IOException {
507         write(new File(fileName), s);
508     }
509 
510     public static void write(String fileName, String s, boolean lazy)
511         throws IOException {
512 
513         write(new File(fileName), s, lazy);
514     }
515 
516     public static void write(String pathName, String fileName, String s)
517         throws IOException {
518 
519         write(new File(pathName, fileName), s);
520     }
521 
522     public static void write(
523             String pathName, String fileName, String s, boolean lazy)
524         throws IOException {
525 
526         write(new File(pathName, fileName), s, lazy);
527     }
528 
529     public static void write(File file, String s) throws IOException {
530         write(file, s, false);
531     }
532 
533     public static void write(File file, String s, boolean lazy)
534         throws IOException {
535 
536         write(file, s, lazy, false);
537     }
538 
539     public static void write(File file, String s, boolean lazy, boolean append)
540         throws IOException {
541 
542         if (file.getParent() != null) {
543             mkdirs(file.getParent());
544         }
545 
546         if (lazy && file.exists()) {
547             String content = read(file);
548 
549             if (content.equals(s)) {
550                 return;
551             }
552         }
553 
554         BufferedWriter bw = new BufferedWriter(new FileWriter(file, append));
555 
556         bw.write(s);
557 
558         bw.close();
559     }
560 
561     public static void write(String fileName, byte[] byteArray)
562         throws IOException {
563 
564         write(new File(fileName), byteArray);
565     }
566 
567     public static void write(File file, byte[] byteArray) throws IOException {
568         if (file.getParent() != null) {
569             mkdirs(file.getParent());
570         }
571 
572         FileOutputStream fos = new FileOutputStream(file);
573 
574         fos.write(byteArray);
575 
576         fos.close();
577     }
578 
579     public static void write(String fileName, InputStream in)
580         throws IOException {
581 
582         write(fileName, getBytes(in));
583     }
584 
585     public static void write(File file, InputStream in) throws IOException {
586         write(file, getBytes(in));
587     }
588 
589     private static Log _log = LogFactory.getLog(FileUtil.class);
590 
591 }