KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > myvietnam > mvncore > util > FileUtil


1 /*
2  * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/util/FileUtil.java,v 1.39 2006/04/15 02:59:20 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.39 $
5  * $Date: 2006/04/15 02:59:20 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding MyVietnam and MyVietnam CoreLib
12  * MUST remain intact in the scripts and source code.
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  *
28  * Correspondence and Marketing Questions can be sent to:
29  * info at MyVietnam net
30  *
31  * @author: Minh Nguyen
32  * @author: Mai Nguyen
33  */

34 package net.myvietnam.mvncore.util;
35
36 import java.io.*;
37 import java.net.URL JavaDoc;
38 import java.text.DecimalFormat JavaDoc;
39
40 import net.myvietnam.mvncore.exception.BadInputException;
41 import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
42 import org.apache.commons.logging.Log;
43 import org.apache.commons.logging.LogFactory;
44
45 public final class FileUtil {
46
47     private static Log log = LogFactory.getLog(FileUtil.class);
48
49     private static FileUtil instance = new FileUtil();
50
51     private static String JavaDoc servletClassesPath = null;
52
53     private FileUtil() { // prevent instantiation
54
}
55
56     public static void checkGoodFilePath(String JavaDoc str) throws BadInputException {
57         byte[] s = str.getBytes();
58         int length = s.length;
59         byte b = 0;
60
61         for (int i = 0; i < length; i++) {
62             b = s[i];
63             if ((b == '*') ||
64                 (b == '?') ||
65                 (b == '<') ||
66                 (b == '>') ||
67                 (b == '"') ||
68                 (b == '|') ||
69                 (b == '\0')) {//null char : is it correct ????
70
// not good char, throw an BadInputException
71
//@todo : localize me
72
throw new BadInputException("The string '" + DisableHtmlTagFilter.filter(str) + "' is not a good file path. Reason: character '" + (char)(b) + "' is not allowed.");
73             }
74         }// for
75
}
76
77     public static void checkGoodFileName(String JavaDoc str) throws BadInputException {
78         // must be a good file path first
79
checkGoodFilePath(str);
80         byte[] s = str.getBytes();
81         int length = s.length;
82         byte b = 0;
83
84         for (int i = 0; i < length; i++) {
85             b = s[i];
86             if ((b == '/') ||
87                 (b == '\\') ||
88                 (b == ':')) {
89                 // not good char, throw an BadInputException
90
//@todo : localize me
91
throw new BadInputException("The string '" + DisableHtmlTagFilter.filter(str) + "' is not a good file name. Reason: character '" + (char)(b) + "' is not allowed.");
92             }
93         }// for
94
}
95
96     public static void createDir(String JavaDoc dir, boolean ignoreIfExitst) throws IOException {
97         File file = new File(dir);
98
99         if (ignoreIfExitst && file.exists()) {
100             return;
101         }
102
103         if ( file.mkdir() == false) {
104             throw new IOException("Cannot create the directory = " + dir);
105         }
106     }
107
108     public static void createDirs(String JavaDoc dir, boolean ignoreIfExitst) throws IOException {
109         File file = new File(dir);
110
111         if (ignoreIfExitst && file.exists()) {
112             return;
113         }
114
115         if ( file.mkdirs() == false) {
116             throw new IOException("Cannot create directories = " + dir);
117         }
118     }
119
120     public static void deleteFile(String JavaDoc filename) throws IOException {
121         File file = new File(filename);
122         log.trace("Delete file = " + filename);
123         if (file.isDirectory()) {
124             throw new IOException("IOException -> BadInputException: not a file.");
125         }
126         if (file.exists() == false) {
127             throw new IOException("IOException -> BadInputException: file is not exist.");
128         }
129         if (file.delete() == false) {
130             throw new IOException("Cannot delete file. filename = " + filename);
131         }
132     }
133
134     public static void deleteDir(File dir) throws IOException {
135         if (dir.isFile()) throw new IOException("IOException -> BadInputException: not a directory.");
136         File[] files = dir.listFiles();
137         if (files != null) {
138             for (int i = 0; i < files.length; i++) {
139                 File file = files[i];
140                 if (file.isFile()) {
141                     file.delete();
142                 } else {
143                     deleteDir(file);
144                 }
145             }
146         }//if
147
dir.delete();
148     }
149
150     public static long getDirLength(File dir) throws IOException {
151         if (dir.isFile()) throw new IOException("BadInputException: not a directory.");
152         long size = 0;
153         File[] files = dir.listFiles();
154         if (files != null) {
155             for (int i = 0; i < files.length; i++) {
156                 File file = files[i];
157                 long length = 0;
158                 if (file.isFile()) {
159                     length = file.length();
160                 } else {
161                     length = getDirLength(file);
162                 }
163                 size += length;
164             }//for
165
}//if
166
return size;
167     }
168
169     public static long getDirLength_onDisk(File dir) throws IOException {
170         if (dir.isFile()) throw new IOException("BadInputException: not a directory.");
171         long size = 0;
172         File[] files = dir.listFiles();
173         if (files != null) {
174             for (int i = 0; i < files.length; i++) {
175                 File file = files[i];
176                 long length = 0;
177                 if (file.isFile()) {
178                     length = file.length();
179                 } else {
180                     length = getDirLength_onDisk(file);
181                 }
182                 double mod = Math.ceil(((double)length)/512);
183                 if (mod == 0) mod = 1;
184                 length = ((long)mod) * 512;
185                 size += length;
186             }
187         }//if
188
return size;
189     }
190
191     public static void emptyFile(String JavaDoc srcFilename) throws IOException {
192         File srcFile = new File(srcFilename);
193         if (!srcFile.exists()) {
194             throw new FileNotFoundException("Cannot find the file: " + srcFile.getAbsolutePath());
195         }
196         if (!srcFile.canWrite()) {
197             throw new IOException("Cannot write the file: " + srcFile.getAbsolutePath());
198         }
199
200         FileOutputStream outputStream = new FileOutputStream(srcFilename);
201         outputStream.close();
202     }
203
204     public static void copyFile(String JavaDoc srcFilename, String JavaDoc destFilename, boolean overwrite) throws IOException {
205
206         File srcFile = new File(srcFilename);
207         if (!srcFile.exists()) {
208             throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath());
209         }
210         if (!srcFile.canRead()) {
211             throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath());
212         }
213
214         File destFile = new File(destFilename);
215         if (overwrite == false) {
216             if (destFile.exists()) return;
217         } else {
218             if (destFile.exists()) {
219                 if (!destFile.canWrite()) {
220                     throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
221                 }
222             } else {
223                 if (!destFile.createNewFile()) {
224                     throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
225                 }
226             }
227         }
228
229         BufferedInputStream inputStream = null;
230         BufferedOutputStream outputStream = null;
231         byte[] block = new byte[1024];
232         try {
233             inputStream = new BufferedInputStream(new FileInputStream(srcFile));
234             outputStream = new BufferedOutputStream(new FileOutputStream(destFile));
235             while (true) {
236                 int readLength = inputStream.read(block);
237                 if (readLength == -1) break;// end of file
238
outputStream.write(block, 0, readLength);
239             }
240         } finally {
241             if (inputStream != null) {
242                 try {
243                     inputStream.close();
244                 } catch (IOException ex) {
245                     // just ignore
246
}
247             }
248             if (outputStream != null) {
249                 try {
250                     outputStream.close();
251                 } catch (IOException ex) {
252                     // just ignore
253
}
254             }
255         }
256     }
257
258     //@todo: why this method does not close the inputStream ???
259
public static byte[] getBytes(InputStream inputStream) throws IOException {
260         BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
261         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
262         byte[] block = new byte[4096];
263         while (true) {
264             int readLength = bufferedInputStream.read(block);
265             if (readLength == -1) break;// end of file
266
byteArrayOutputStream.write(block, 0, readLength);
267         }
268         byte[] retValue = byteArrayOutputStream.toByteArray();
269         byteArrayOutputStream.close();
270         return retValue;
271     }
272
273     public static String JavaDoc getFileName(String JavaDoc fullFilePath) {
274         if (fullFilePath == null) {
275             return "";
276         }
277         int index1 = fullFilePath.lastIndexOf('/');
278         int index2 = fullFilePath.lastIndexOf('\\');
279
280         //index is the maximum value of index1 and index2
281
int index = (index1 > index2) ? index1 : index2;
282         if (index == -1) {
283             // not found the path separator
284
return fullFilePath;
285         }
286         String JavaDoc fileName = fullFilePath.substring(index + 1);
287         return fileName;
288     }
289
290     /**
291      * This method write srcFile to the output, and does not close the output
292      * @param srcFile File the source (input) file
293      * @param output OutputStream the stream to write to, this method will not buffered the output
294      * @throws IOException
295      */

296     public static void popFile(File srcFile, OutputStream output) throws IOException {
297
298         BufferedInputStream input = null;
299         byte[] block = new byte[4096];
300         try {
301             input = new BufferedInputStream(new FileInputStream(srcFile), 4096);
302             while (true) {
303                 int length = input.read(block);
304                 if (length == -1) break;// end of file
305
output.write(block, 0, length);
306             }
307         } finally {
308             if (input != null) {
309                 try {
310                     input.close();
311                 } catch (IOException ex) {
312                     // just ignore
313
}
314             }
315         }
316     }
317
318     /**
319      * This method could be used to override the path to WEB-INF/classes
320      * It can be set when the web app is inited
321      * @param path String : new path to override the default path
322      */

323     public static void setServletClassesPath(String JavaDoc path) {
324         log.debug("FileUtil.setServletClassesPath called with path = " + path);
325
326         servletClassesPath = path;
327
328         if (servletClassesPath == null) {
329             // From mvnForum.com thread 2243:
330
// I am deploying the MVNForum as an ear in Linux box so context real path turns out to be null.
331
return;
332         }
333         if (servletClassesPath.endsWith(File.separator) == false) {
334             servletClassesPath = servletClassesPath + File.separatorChar;
335             log.debug("FileUtil.setServletClassesPath change path to value = " + servletClassesPath);
336         }
337     }
338
339     /**
340      * This function is used to get the classpath of a reference of one class
341      * First, this method tries to get the path from system properties
342      * named "mvncore.context.path" (can be configed in web.xml). If it cannot
343      * find this parameter, then it will tries to load from the ClassLoader
344      * @todo FIXME: load from ClassLoader is not correct on Resin/Linux
345      */

346     public static String JavaDoc getServletClassesPath() {
347         if (servletClassesPath == null) {
348             String JavaDoc strPath = System.getProperty("mvncore.context.path");
349             if (strPath != null && (strPath.length() > 0)) {
350                 servletClassesPath = strPath;
351             } else {
352                 ClassLoader JavaDoc classLoader = instance.getClass().getClassLoader();
353                 URL JavaDoc url = classLoader.getResource("/");
354                 if (url == null) {
355                     // not run on the Servlet environment
356
servletClassesPath = ".";
357                 } else {
358                     servletClassesPath = url.getPath();
359                 }
360             }
361             log.debug("servletClassesPath = " + servletClassesPath);
362             if (servletClassesPath.endsWith(File.separator) == false) {
363                 servletClassesPath = servletClassesPath + File.separatorChar;
364                 //log.warn("servletClassesPath does not end with /: " + servletClassesPath);
365
}
366         }
367         return servletClassesPath;
368     }
369
370     /**
371      * This method create a file text/css
372      * NOTE: This method closes the inputStream after it have done its work.
373      *
374      * @param inputStream the stream of a text/css file
375      * @param cssFile the output file, have the ".css" extension or orther extension
376      * @throws IOException
377      * @throws BadInputException
378      * @throws AssertionException
379      */

380     public static void createTextFile(InputStream inputStream, String JavaDoc textFile)
381         throws IOException {
382
383         if (inputStream == null) {
384             throw new IllegalArgumentException JavaDoc("Does not accept null input");
385         }
386         OutputStream outputStream = null;
387         try {
388             byte[] srcByte = FileUtil.getBytes(inputStream);
389             outputStream = new FileOutputStream(textFile);
390             outputStream.write(srcByte);
391             return;
392         } catch (IOException e) {
393             log.error("Error", e);
394             throw e;
395         } finally { // this finally is very important
396
inputStream.close();
397             if (outputStream != null) outputStream.close();
398         }
399     }
400
401     /**
402      * Write content to a fileName with the destEncoding
403      *
404      * @param content String
405      * @param fileName String
406      * @param destEncoding String
407      * @throws FileNotFoundException
408      * @throws IOException
409      */

410     public static void writeFile(String JavaDoc content, String JavaDoc fileName, String JavaDoc destEncoding)
411         throws FileNotFoundException, IOException {
412
413         File file = null;
414         try {
415             file = new File(fileName);
416             if (file.isFile() == false) {
417                 throw new IOException("'" + fileName + "' is not a file.");
418             }
419             if (file.canWrite() == false) {
420                 throw new IOException("'" + fileName + "' is a read-only file.");
421             }
422         } finally {
423             // we dont have to close File here
424
}
425
426         BufferedWriter out = null;
427         try {
428             FileOutputStream fos = new FileOutputStream(fileName);
429             out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding));
430
431             out.write(content);
432             out.flush();
433         } catch (FileNotFoundException fe) {
434             log.error("Error", fe);
435             throw fe;
436         } catch (IOException e) {
437             log.error("Error", e);
438             throw e;
439         } finally {
440             try {
441                 if (out != null) out.close();
442             } catch (IOException ex) {}
443         }
444     }
445
446     public static String JavaDoc readFile(String JavaDoc fileName, String JavaDoc srcEncoding)
447         throws FileNotFoundException, IOException {
448
449         File file = null;
450         try {
451             file = new File(fileName);
452             if (file.isFile() == false) {
453                 throw new IOException("'" + fileName + "' is not a file.");
454             }
455         } finally {
456             // we dont have to close File here
457
}
458
459         BufferedReader reader = null;
460         try {
461             StringBuffer JavaDoc result = new StringBuffer JavaDoc(1024);
462             FileInputStream fis = new FileInputStream(fileName);
463             reader = new BufferedReader(new InputStreamReader(fis, srcEncoding));
464
465             char[] block = new char[512];
466             while (true) {
467                 int readLength = reader.read(block);
468                 if (readLength == -1) break;// end of file
469
result.append(block, 0, readLength);
470             }
471             return result.toString();
472         } catch (FileNotFoundException fe) {
473             log.error("Error", fe);
474             throw fe;
475         } catch (IOException e) {
476             log.error("Error", e);
477             throw e;
478         } finally {
479             try {
480                 if (reader != null) reader.close();
481             } catch (IOException ex) {}
482         }
483     }
484
485     /*
486      * 1 ABC
487      * 2 abC Gia su doc tu dong 1 lay ca thay 5 dong => 1 --> 5
488      * 3 ABC
489      */

490     public static String JavaDoc[] getLastLines(File file, int linesToReturn)
491         throws IOException, FileNotFoundException {
492
493         final int AVERAGE_CHARS_PER_LINE = 250;
494         final int BYTES_PER_CHAR = 2;
495
496         RandomAccessFile randomAccessFile = null;
497         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(linesToReturn * AVERAGE_CHARS_PER_LINE);
498         int lineTotal = 0;
499         try {
500             randomAccessFile = new RandomAccessFile(file, "r");
501             long byteTotal = randomAccessFile.length();
502             long byteEstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE * BYTES_PER_CHAR;
503
504             long offset = byteTotal - byteEstimateToRead;
505             if (offset < 0) {
506                 offset = 0;
507             }
508
509             randomAccessFile.seek(offset);
510             //log.debug("SKIP IS ::" + offset);
511

512             String JavaDoc line = null;
513             String JavaDoc lineUTF8 = null;
514             while ((line = randomAccessFile.readLine()) != null) {
515                 lineUTF8 = new String JavaDoc(line.getBytes("ISO8859_1"), "UTF-8");
516                 lineTotal++;
517                 buffer.append(lineUTF8).append("\n");
518             }
519         } finally {
520             if (randomAccessFile != null) {
521                 try {
522                     randomAccessFile.close();
523                 } catch (IOException ex) {
524                 }
525             }
526         }
527
528         String JavaDoc[] resultLines = new String JavaDoc[linesToReturn];
529         BufferedReader in = null;
530         try {
531             in = new BufferedReader(new StringReader(buffer.toString()));
532
533             int start = lineTotal /* + 2 */ - linesToReturn; // Ex : 55 - 10 = 45 ~ offset
534
if (start < 0) start = 0; // not start line
535
for (int i = 0; i < start; i++) {
536                 in.readLine(); // loop until the offset. Ex: loop 0, 1 ~~ 2 lines
537
}
538
539             int i = 0;
540             String JavaDoc line = null;
541             while ((line = in.readLine()) != null) {
542                 resultLines[i] = line;
543                 i++;
544             }
545         } catch (IOException ie) {
546             log.error("Error" + ie);
547             throw ie;
548         } finally {
549             if (in != null) {
550                 try {
551                     in.close();
552                 } catch (IOException ex) {
553                 }
554             }
555         }
556         return resultLines;
557     }
558
559     public static String JavaDoc getHumanSize(long size) {
560
561         int sizeToStringLength = String.valueOf(size).length();
562         String JavaDoc humanSize = "";
563         DecimalFormat JavaDoc formatter = new DecimalFormat JavaDoc("##0.##");
564         if (sizeToStringLength > 9) {
565             humanSize += formatter.format((double) size / (1024 * 1024 * 1024)) + " GB";
566         } else if (sizeToStringLength > 6) {
567             humanSize += formatter.format((double) size / (1024 * 1024)) + " MB";
568         } else if (sizeToStringLength > 3) {
569             humanSize += formatter.format((double) size / 1024) + " KB";
570         } else {
571             humanSize += String.valueOf(size) + " Bytes";
572         }
573         return humanSize;
574     }
575 }
576
Popular Tags