1   /**
2    * Copyright (c) 2000-2007 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 void append(String fileName, String s) throws IOException {
62          append(new File(fileName), s);
63      }
64  
65      public static void append(String pathName, String fileName, String s)
66          throws IOException {
67  
68          append(new File(pathName, fileName), s);
69      }
70  
71      public static void append(File file, String s) throws IOException {
72          if (file.getParent() != null) {
73              mkdirs(file.getParent());
74          }
75  
76          BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
77  
78          bw.write(s);
79  
80          bw.close();
81      }
82  
83      public static void copyDirectory(
84          String sourceDirName, String destinationDirName) {
85  
86          copyDirectory(new File(sourceDirName), new File(destinationDirName));
87      }
88  
89      public static void copyDirectory(File source, File destination) {
90          if (source.exists() && source.isDirectory()) {
91              if (!destination.exists()) {
92                  destination.mkdirs();
93              }
94  
95              File[] fileArray = source.listFiles();
96  
97              for (int i = 0; i < fileArray.length; i++) {
98                  if (fileArray[i].isDirectory()) {
99                      copyDirectory(
100                         fileArray[i],
101                         new File(destination.getPath() + File.separator
102                             + fileArray[i].getName()));
103                 }
104                 else {
105                     copyFile(
106                         fileArray[i],
107                         new File(destination.getPath() + File.separator
108                             + fileArray[i].getName()));
109                 }
110             }
111         }
112     }
113 
114     public static void copyFile(String source, String destination) {
115         copyFile(source, destination, false);
116     }
117 
118     public static void copyFile(
119         String source, String destination, boolean lazy) {
120 
121         copyFile(new File(source), new File(destination), lazy);
122     }
123 
124     public static void copyFile(File source, File destination) {
125         copyFile(source, destination, false);
126     }
127 
128     public static void copyFile(File source, File destination, boolean lazy) {
129         if (!source.exists()) {
130             return;
131         }
132 
133         if (lazy) {
134             String oldContent = null;
135 
136             try {
137                 oldContent = read(source);
138             }
139             catch (Exception e) {
140                 return;
141             }
142 
143             String newContent = null;
144 
145             try {
146                 newContent = read(destination);
147             }
148             catch (Exception e) {
149             }
150 
151             if (oldContent == null || !oldContent.equals(newContent)) {
152                 copyFile(source, destination, false);
153             }
154         }
155         else {
156             if ((destination.getParentFile() != null) &&
157                 (!destination.getParentFile().exists())) {
158 
159                 destination.getParentFile().mkdirs();
160             }
161 
162             try {
163                 FileChannel srcChannel =
164                     new FileInputStream(source).getChannel();
165                 FileChannel dstChannel =
166                     new FileOutputStream(destination).getChannel();
167 
168                 dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
169 
170                 srcChannel.close();
171                 dstChannel.close();
172             }
173             catch (IOException ioe) {
174                 _log.error(ioe.getMessage());
175             }
176         }
177     }
178 
179     public static boolean delete(String file) {
180         return delete(new File(file));
181     }
182 
183     public static boolean delete(File file) {
184         if (file.exists()) {
185             return file.delete();
186         }
187         else {
188             return false;
189         }
190     }
191 
192     public static void deltree(String directory) {
193         deltree(new File(directory));
194     }
195 
196     public static void deltree(File directory) {
197         if (directory.exists() && directory.isDirectory()) {
198             File[] fileArray = directory.listFiles();
199 
200             for (int i = 0; i < fileArray.length; i++) {
201                 if (fileArray[i].isDirectory()) {
202                     deltree(fileArray[i]);
203                 }
204                 else {
205                     fileArray[i].delete();
206                 }
207             }
208 
209             directory.delete();
210         }
211     }
212 
213     public static boolean exists(String fileName) {
214         return exists(new File(fileName));
215     }
216 
217     public static boolean exists(File file) {
218         return file.exists();
219     }
220 
221     public static String getAbsolutePath(File file) {
222         return StringUtil.replace(
223             file.getAbsolutePath(), StringPool.BACK_SLASH, StringPool.SLASH);
224     }
225 
226     public static byte[] getBytes(File file) throws IOException {
227         if ((file == null) || !file.exists()) {
228             return null;
229         }
230 
231         FileInputStream in = new FileInputStream(file);
232 
233         byte[] bytes = getBytes(in, (int)file.length());
234 
235         in.close();
236 
237         return bytes;
238     }
239 
240     public static byte[] getBytes(InputStream in) throws IOException {
241         return getBytes(in, -1);
242     }
243 
244     public static byte[] getBytes(InputStream in, int bufferSize)
245         throws IOException {
246 
247         ByteArrayMaker out = null;
248 
249         if (bufferSize <= 0) {
250             out = new ByteArrayMaker();
251         }
252         else {
253             out = new ByteArrayMaker(bufferSize);
254         }
255 
256         boolean createBuffered = false;
257 
258         try {
259             if (!(in instanceof BufferedInputStream)) {
260                 in = new BufferedInputStream(in);
261 
262                 createBuffered = true;
263             }
264 
265             int c = in.read();
266 
267             while (c != -1) {
268                 out.write(c);
269 
270                 c = in.read();
271             }
272         }
273         finally {
274             if (createBuffered) {
275                 in.close();
276             }
277         }
278 
279         out.close();
280 
281         return out.toByteArray();
282     }
283 
284     public static String getExtension(String fileName) {
285         if (fileName == null) {
286             return null;
287         }
288 
289         int pos = fileName.lastIndexOf(StringPool.PERIOD);
290 
291         if (pos != -1) {
292             return fileName.substring(pos + 1, fileName.length());
293         }
294         else {
295             return null;
296         }
297     }
298 
299     public static String getPath(String fullFileName) {
300         int pos = fullFileName.lastIndexOf(StringPool.SLASH);
301 
302         if (pos == -1) {
303             pos = fullFileName.lastIndexOf(StringPool.BACK_SLASH);
304         }
305 
306         String shortFileName = fullFileName.substring(0, pos);
307 
308         if (Validator.isNull(shortFileName)) {
309             return StringPool.SLASH;
310         }
311 
312         return shortFileName;
313     }
314 
315     public static String getShortFileName(String fullFileName) {
316         int pos = fullFileName.lastIndexOf(StringPool.SLASH);
317 
318         if (pos == -1) {
319             pos = fullFileName.lastIndexOf(StringPool.BACK_SLASH);
320         }
321 
322         String shortFileName =
323             fullFileName.substring(pos + 1, fullFileName.length());
324 
325         return shortFileName;
326     }
327 
328     public static String[] listDirs(String fileName) throws IOException {
329         return listDirs(new File(fileName));
330     }
331 
332     public static String[] listDirs(File file) throws IOException {
333         List dirs = new ArrayList();
334 
335         File[] fileArray = file.listFiles();
336 
337         for (int i = 0; i < fileArray.length; i++) {
338             if (fileArray[i].isDirectory()) {
339                 dirs.add(fileArray[i].getName());
340             }
341         }
342 
343         return (String[])dirs.toArray(new String[0]);
344     }
345 
346     public static String[] listFiles(String fileName) throws IOException {
347         if (Validator.isNull(fileName)) {
348             return new String[0];
349         }
350 
351         return listFiles(new File(fileName));
352     }
353 
354     public static String[] listFiles(File file) throws IOException {
355         List files = new ArrayList();
356 
357         File[] fileArray = file.listFiles();
358 
359         for (int i = 0; (fileArray != null) && (i < fileArray.length); i++) {
360             if (fileArray[i].isFile()) {
361                 files.add(fileArray[i].getName());
362             }
363         }
364 
365         return (String[])files.toArray(new String[0]);
366     }
367 
368     public static void mkdirs(String pathName) {
369         File file = new File(pathName);
370 
371         file.mkdirs();
372     }
373 
374     public static boolean move(
375         String sourceFileName, String destinationFileName) {
376 
377         return move(new File(sourceFileName), new File(destinationFileName));
378     }
379 
380     public static boolean move(File source, File destination) {
381         if (!source.exists()) {
382             return false;
383         }
384 
385         destination.delete();
386 
387         return source.renameTo(destination);
388     }
389 
390     public static String read(String fileName) throws IOException {
391         return read(new File(fileName));
392     }
393 
394     public static String read(File file) throws IOException {
395         return read(file, false);
396     }
397 
398     public static String read(File file, boolean raw) throws IOException {
399         FileInputStream fis = new FileInputStream(file);
400 
401         byte[] bytes = new byte[fis.available()];
402 
403         fis.read(bytes);
404 
405         fis.close();
406 
407         String s = new String(bytes);
408 
409         if (raw) {
410             return s;
411         }
412         else {
413             return StringUtil.replace(
414                 s, StringPool.RETURN_NEW_LINE, StringPool.NEW_LINE);
415         }
416     }
417 
418     public static File[] sortFiles(File[] files) {
419         Arrays.sort(files, new FileComparator());
420 
421         List directoryList = new ArrayList();
422         List fileList = new ArrayList();
423 
424         for (int i = 0; i < files.length; i++) {
425             if (files[i].isDirectory()) {
426                 directoryList.add(files[i]);
427             }
428             else {
429                 fileList.add(files[i]);
430             }
431         }
432 
433         directoryList.addAll(fileList);
434 
435         return (File[])directoryList.toArray(new File[0]);
436     }
437 
438     public static String replaceSeparator(String fileName) {
439         return StringUtil.replace(
440             fileName, StringPool.BACK_SLASH, StringPool.SLASH);
441     }
442 
443     public static List toList(Reader reader) {
444         List list = new ArrayList();
445 
446         try {
447             BufferedReader br = new BufferedReader(reader);
448 
449             String line = null;
450 
451             while ((line = br.readLine()) != null) {
452                 list.add(line);
453             }
454 
455             br.close();
456         }
457         catch (IOException ioe) {
458         }
459 
460         return list;
461     }
462 
463     public static List toList(String fileName) {
464         try {
465             return toList(new FileReader(fileName));
466         }
467         catch (IOException ioe) {
468             return new ArrayList();
469         }
470     }
471 
472     public static Properties toProperties(FileInputStream fis) {
473         Properties props = new Properties();
474 
475         try {
476             props.load(fis);
477         }
478         catch (IOException ioe) {
479         }
480 
481         return props;
482     }
483 
484     public static Properties toProperties(String fileName) {
485         try {
486             return toProperties(new FileInputStream(fileName));
487         }
488         catch (IOException ioe) {
489             return new Properties();
490         }
491     }
492 
493     public static void write(String fileName, String s) throws IOException {
494         write(new File(fileName), s);
495     }
496 
497     public static void write(String fileName, String s, boolean lazy)
498         throws IOException {
499 
500         write(new File(fileName), s, lazy);
501     }
502 
503     public static void write(String pathName, String fileName, String s)
504         throws IOException {
505 
506         write(new File(pathName, fileName), s);
507     }
508 
509     public static void write(
510             String pathName, String fileName, String s, boolean lazy)
511         throws IOException {
512 
513         write(new File(pathName, fileName), s, lazy);
514     }
515 
516     public static void write(File file, String s) throws IOException {
517         write(file, s, false);
518     }
519 
520     public static void write(File file, String s, boolean lazy)
521         throws IOException {
522 
523         write(file, s, lazy, false);
524     }
525 
526     public static void write(File file, String s, boolean lazy, boolean append)
527         throws IOException {
528 
529         if (file.getParent() != null) {
530             mkdirs(file.getParent());
531         }
532 
533         if (lazy && file.exists()) {
534             String content = read(file);
535 
536             if (content.equals(s)) {
537                 return;
538             }
539         }
540 
541         BufferedWriter bw = new BufferedWriter(new FileWriter(file, append));
542 
543         bw.write(s);
544 
545         bw.close();
546     }
547 
548     public static void write(String fileName, byte[] byteArray)
549         throws IOException {
550 
551         write(new File(fileName), byteArray);
552     }
553 
554     public static void write(File file, byte[] byteArray) throws IOException {
555         if (file.getParent() != null) {
556             mkdirs(file.getParent());
557         }
558 
559         FileOutputStream fos = new FileOutputStream(file);
560 
561         fos.write(byteArray);
562 
563         fos.close();
564     }
565 
566     public static void write(String fileName, InputStream in)
567         throws IOException {
568 
569         write(fileName, getBytes(in));
570     }
571 
572     public static void write(File file, InputStream in) throws IOException {
573         write(file, getBytes(in));
574     }
575 
576     private static Log _log = LogFactory.getLog(FileUtil.class);
577 
578 }