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.GetterUtil;
27  import com.liferay.portal.kernel.util.StringMaker;
28  import com.liferay.portal.kernel.util.StringPool;
29  import com.liferay.portal.kernel.util.StringUtil;
30  import com.liferay.portal.kernel.util.Validator;
31  
32  import java.io.BufferedInputStream;
33  import java.io.BufferedReader;
34  import java.io.BufferedWriter;
35  import java.io.File;
36  import java.io.FileInputStream;
37  import java.io.FileOutputStream;
38  import java.io.FileReader;
39  import java.io.IOException;
40  import java.io.InputStream;
41  import java.io.OutputStreamWriter;
42  import java.io.Reader;
43  
44  import java.nio.channels.FileChannel;
45  
46  import java.util.ArrayList;
47  import java.util.Arrays;
48  import java.util.List;
49  import java.util.Properties;
50  
51  import org.apache.commons.logging.Log;
52  import org.apache.commons.logging.LogFactory;
53  
54  import org.mozilla.intl.chardet.nsDetector;
55  import org.mozilla.intl.chardet.nsPSMDetector;
56  
57  /**
58   * <a href="FileUtil.java.html"><b><i>View Source</i></b></a>
59   *
60   * @author Brian Wing Shun Chan
61   * @author Alexander Chow
62   *
63   */
64  public class FileUtil {
65  
66      public static final String ENCODING = GetterUtil.getString(
67          SystemProperties.get("file.encoding"), StringPool.UTF8);
68  
69      public static void copyDirectory(
70          String sourceDirName, String destinationDirName) {
71  
72          copyDirectory(new File(sourceDirName), new File(destinationDirName));
73      }
74  
75      public static void copyDirectory(File source, File destination) {
76          if (source.exists() && source.isDirectory()) {
77              if (!destination.exists()) {
78                  destination.mkdirs();
79              }
80  
81              File[] fileArray = source.listFiles();
82  
83              for (int i = 0; i < fileArray.length; i++) {
84                  if (fileArray[i].isDirectory()) {
85                      copyDirectory(
86                          fileArray[i],
87                          new File(destination.getPath() + File.separator
88                              + fileArray[i].getName()));
89                  }
90                  else {
91                      copyFile(
92                          fileArray[i],
93                          new File(destination.getPath() + File.separator
94                              + fileArray[i].getName()));
95                  }
96              }
97          }
98      }
99  
100     public static void copyFile(String source, String destination) {
101         copyFile(source, destination, false);
102     }
103 
104     public static void copyFile(
105         String source, String destination, boolean lazy) {
106 
107         copyFile(new File(source), new File(destination), lazy);
108     }
109 
110     public static void copyFile(File source, File destination) {
111         copyFile(source, destination, false);
112     }
113 
114     public static void copyFile(File source, File destination, boolean lazy) {
115         if (!source.exists()) {
116             return;
117         }
118 
119         if (lazy) {
120             String oldContent = null;
121 
122             try {
123                 oldContent = read(source);
124             }
125             catch (Exception e) {
126                 return;
127             }
128 
129             String newContent = null;
130 
131             try {
132                 newContent = read(destination);
133             }
134             catch (Exception e) {
135             }
136 
137             if (oldContent == null || !oldContent.equals(newContent)) {
138                 copyFile(source, destination, false);
139             }
140         }
141         else {
142             if ((destination.getParentFile() != null) &&
143                 (!destination.getParentFile().exists())) {
144 
145                 destination.getParentFile().mkdirs();
146             }
147 
148             try {
149                 FileChannel srcChannel =
150                     new FileInputStream(source).getChannel();
151                 FileChannel dstChannel =
152                     new FileOutputStream(destination).getChannel();
153 
154                 dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
155 
156                 srcChannel.close();
157                 dstChannel.close();
158             }
159             catch (IOException ioe) {
160                 _log.error(ioe.getMessage());
161             }
162         }
163     }
164 
165     public static File createTempFile() {
166         return createTempFile(null);
167     }
168 
169     public static File createTempFile(String extension) {
170         StringMaker sm = new StringMaker();
171 
172         sm.append(SystemProperties.get(SystemProperties.TMP_DIR));
173         sm.append(StringPool.SLASH);
174         sm.append(Time.getTimestamp());
175         sm.append(PwdGenerator.getPassword(PwdGenerator.KEY2, 8));
176 
177         if (Validator.isNotNull(extension)) {
178             sm.append(StringPool.PERIOD);
179             sm.append(extension);
180         }
181 
182         return new File(sm.toString());
183     }
184 
185     public static boolean delete(String file) {
186         return delete(new File(file));
187     }
188 
189     public static boolean delete(File file) {
190         if (file.exists()) {
191             return file.delete();
192         }
193         else {
194             return false;
195         }
196     }
197 
198     public static void deltree(String directory) {
199         deltree(new File(directory));
200     }
201 
202     public static void deltree(File directory) {
203         if (directory.exists() && directory.isDirectory()) {
204             File[] fileArray = directory.listFiles();
205 
206             for (int i = 0; i < fileArray.length; i++) {
207                 if (fileArray[i].isDirectory()) {
208                     deltree(fileArray[i]);
209                 }
210                 else {
211                     fileArray[i].delete();
212                 }
213             }
214 
215             directory.delete();
216         }
217     }
218 
219     public static boolean exists(String fileName) {
220         return exists(new File(fileName));
221     }
222 
223     public static boolean exists(File file) {
224         return file.exists();
225     }
226 
227     public static String getAbsolutePath(File file) {
228         return StringUtil.replace(
229             file.getAbsolutePath(), StringPool.BACK_SLASH, StringPool.SLASH);
230     }
231 
232     public static byte[] getBytes(File file) throws IOException {
233         if ((file == null) || !file.exists()) {
234             return null;
235         }
236 
237         FileInputStream in = new FileInputStream(file);
238 
239         byte[] bytes = getBytes(in, (int)file.length());
240 
241         in.close();
242 
243         return bytes;
244     }
245 
246     public static byte[] getBytes(InputStream in) throws IOException {
247         return getBytes(in, -1);
248     }
249 
250     public static byte[] getBytes(InputStream in, int bufferSize)
251         throws IOException {
252 
253         ByteArrayMaker out = null;
254 
255         if (bufferSize <= 0) {
256             out = new ByteArrayMaker();
257         }
258         else {
259             out = new ByteArrayMaker(bufferSize);
260         }
261 
262         boolean createBuffered = false;
263 
264         try {
265             if (!(in instanceof BufferedInputStream)) {
266                 in = new BufferedInputStream(in);
267 
268                 createBuffered = true;
269             }
270 
271             int c = in.read();
272 
273             while (c != -1) {
274                 out.write(c);
275 
276                 c = in.read();
277             }
278         }
279         finally {
280             if (createBuffered) {
281                 in.close();
282             }
283         }
284 
285         out.close();
286 
287         return out.toByteArray();
288     }
289 
290     public static String getExtension(String fileName) {
291         if (fileName == null) {
292             return null;
293         }
294 
295         int pos = fileName.lastIndexOf(StringPool.PERIOD);
296 
297         if (pos != -1) {
298             return fileName.substring(pos + 1, fileName.length()).toLowerCase();
299         }
300         else {
301             return null;
302         }
303     }
304 
305     public static String getPath(String fullFileName) {
306         int pos = fullFileName.lastIndexOf(StringPool.SLASH);
307 
308         if (pos == -1) {
309             pos = fullFileName.lastIndexOf(StringPool.BACK_SLASH);
310         }
311 
312         String shortFileName = fullFileName.substring(0, pos);
313 
314         if (Validator.isNull(shortFileName)) {
315             return StringPool.SLASH;
316         }
317 
318         return shortFileName;
319     }
320 
321     public static String getShortFileName(String fullFileName) {
322         int pos = fullFileName.lastIndexOf(StringPool.SLASH);
323 
324         if (pos == -1) {
325             pos = fullFileName.lastIndexOf(StringPool.BACK_SLASH);
326         }
327 
328         String shortFileName =
329             fullFileName.substring(pos + 1, fullFileName.length());
330 
331         return shortFileName;
332     }
333 
334     public static boolean isAscii(File file) throws IOException {
335         boolean ascii = true;
336 
337         nsDetector detector = new nsDetector(nsPSMDetector.ALL);
338 
339         BufferedInputStream bis = new BufferedInputStream(
340             new FileInputStream(file));
341 
342         byte[] buffer = new byte[1024];
343 
344         int len = 0;
345 
346         while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
347             if (ascii) {
348                 ascii = detector.isAscii(buffer, len);
349 
350                 if (!ascii) {
351                     break;
352                 }
353             }
354         }
355 
356         detector.DataEnd();
357 
358         return ascii;
359     }
360 
361     public static String[] listDirs(String fileName) throws IOException {
362         return listDirs(new File(fileName));
363     }
364 
365     public static String[] listDirs(File file) throws IOException {
366         List<String> dirs = new ArrayList<String>();
367 
368         File[] fileArray = file.listFiles();
369 
370         for (int i = 0; i < fileArray.length; i++) {
371             if (fileArray[i].isDirectory()) {
372                 dirs.add(fileArray[i].getName());
373             }
374         }
375 
376         return dirs.toArray(new String[dirs.size()]);
377     }
378 
379     public static String[] listFiles(String fileName) throws IOException {
380         if (Validator.isNull(fileName)) {
381             return new String[0];
382         }
383 
384         return listFiles(new File(fileName));
385     }
386 
387     public static String[] listFiles(File file) throws IOException {
388         List<String> files = new ArrayList<String>();
389 
390         File[] fileArray = file.listFiles();
391 
392         for (int i = 0; (fileArray != null) && (i < fileArray.length); i++) {
393             if (fileArray[i].isFile()) {
394                 files.add(fileArray[i].getName());
395             }
396         }
397 
398         return files.toArray(new String[files.size()]);
399     }
400 
401     public static void mkdirs(String pathName) {
402         File file = new File(pathName);
403 
404         file.mkdirs();
405     }
406 
407     public static boolean move(
408         String sourceFileName, String destinationFileName) {
409 
410         return move(new File(sourceFileName), new File(destinationFileName));
411     }
412 
413     public static boolean move(File source, File destination) {
414         if (!source.exists()) {
415             return false;
416         }
417 
418         destination.delete();
419 
420         return source.renameTo(destination);
421     }
422 
423     public static String read(String fileName) throws IOException {
424         return read(new File(fileName));
425     }
426 
427     public static String read(File file) throws IOException {
428         return read(file, false);
429     }
430 
431     public static String read(File file, boolean raw)
432         throws IOException {
433 
434         FileInputStream fis = new FileInputStream(file);
435 
436         byte[] bytes = new byte[fis.available()];
437 
438         fis.read(bytes);
439 
440         fis.close();
441 
442         String s = new String(bytes, ENCODING);
443 
444         if (raw) {
445             return s;
446         }
447         else {
448             return StringUtil.replace(
449                 s, StringPool.RETURN_NEW_LINE, StringPool.NEW_LINE);
450         }
451     }
452 
453     public static File[] sortFiles(File[] files) {
454         if (files == null) {
455             return null;
456         }
457 
458         Arrays.sort(files, new FileComparator());
459 
460         List<File> directoryList = new ArrayList<File>();
461         List<File> fileList = new ArrayList<File>();
462 
463         for (int i = 0; i < files.length; i++) {
464             if (files[i].isDirectory()) {
465                 directoryList.add(files[i]);
466             }
467             else {
468                 fileList.add(files[i]);
469             }
470         }
471 
472         directoryList.addAll(fileList);
473 
474         return directoryList.toArray(new File[directoryList.size()]);
475     }
476 
477     public static String stripExtension(String fileName) {
478         if (fileName == null) {
479             return null;
480         }
481 
482         int pos = fileName.lastIndexOf(StringPool.PERIOD);
483 
484         if (pos != -1) {
485             return fileName.substring(0, pos);
486         }
487         else {
488             return fileName;
489         }
490     }
491 
492     public static String replaceSeparator(String fileName) {
493         return StringUtil.replace(
494             fileName, StringPool.BACK_SLASH, StringPool.SLASH);
495     }
496 
497     public static List<String> toList(Reader reader) {
498         List<String> list = new ArrayList<String>();
499 
500         try {
501             BufferedReader br = new BufferedReader(reader);
502 
503             String line = null;
504 
505             while ((line = br.readLine()) != null) {
506                 list.add(line);
507             }
508 
509             br.close();
510         }
511         catch (IOException ioe) {
512         }
513 
514         return list;
515     }
516 
517     public static List<String> toList(String fileName) {
518         try {
519             return toList(new FileReader(fileName));
520         }
521         catch (IOException ioe) {
522             return new ArrayList<String>();
523         }
524     }
525 
526     public static Properties toProperties(FileInputStream fis) {
527         Properties props = new Properties();
528 
529         try {
530             props.load(fis);
531         }
532         catch (IOException ioe) {
533         }
534 
535         return props;
536     }
537 
538     public static Properties toProperties(String fileName) {
539         try {
540             return toProperties(new FileInputStream(fileName));
541         }
542         catch (IOException ioe) {
543             return new Properties();
544         }
545     }
546 
547     public static void write(String fileName, String s) throws IOException {
548         write(new File(fileName), s);
549     }
550 
551     public static void write(String fileName, String s, boolean lazy)
552         throws IOException {
553 
554         write(new File(fileName), s, lazy);
555     }
556 
557     public static void write(
558             String fileName, String s, boolean lazy, boolean append)
559         throws IOException {
560 
561         write(new File(fileName), s, lazy, append);
562     }
563 
564     public static void write(String pathName, String fileName, String s)
565         throws IOException {
566 
567         write(new File(pathName, fileName), s);
568     }
569 
570     public static void write(
571             String pathName, String fileName, String s, boolean lazy)
572         throws IOException {
573 
574         write(new File(pathName, fileName), s, lazy);
575     }
576 
577     public static void write(
578             String pathName, String fileName, String s, boolean lazy,
579             boolean append)
580         throws IOException {
581 
582         write(new File(pathName, fileName), s, lazy, append);
583     }
584 
585     public static void write(File file, String s) throws IOException {
586         write(file, s, false);
587     }
588 
589     public static void write(File file, String s, boolean lazy)
590         throws IOException {
591 
592         write(file, s, lazy, false);
593     }
594 
595     public static void write(File file, String s, boolean lazy, boolean append)
596         throws IOException {
597 
598         if (file.getParent() != null) {
599             mkdirs(file.getParent());
600         }
601 
602         if (lazy && file.exists()) {
603             String content = read(file);
604 
605             if (content.equals(s)) {
606                 return;
607             }
608         }
609 
610         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
611             new FileOutputStream(file, append), ENCODING));
612 
613         bw.write(s);
614 
615         bw.close();
616     }
617 
618     public static void write(String fileName, byte[] byteArray)
619         throws IOException {
620 
621         write(new File(fileName), byteArray);
622     }
623 
624     public static void write(File file, byte[] byteArray) throws IOException {
625         if (file.getParent() != null) {
626             mkdirs(file.getParent());
627         }
628 
629         FileOutputStream fos = new FileOutputStream(file);
630 
631         fos.write(byteArray);
632 
633         fos.close();
634     }
635 
636     public static void write(String fileName, InputStream in)
637         throws IOException {
638 
639         write(fileName, getBytes(in));
640     }
641 
642     public static void write(File file, InputStream in) throws IOException {
643         write(file, getBytes(in));
644     }
645 
646     private static Log _log = LogFactory.getLog(FileUtil.class);
647 
648 }