KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > igfay > util > FileUtility


1 package org.igfay.util;
2
3 import java.io.BufferedInputStream JavaDoc;
4 import java.io.BufferedReader JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.FileNotFoundException JavaDoc;
8 import java.io.FileOutputStream JavaDoc;
9 import java.io.FileReader JavaDoc;
10 import java.io.FileWriter JavaDoc;
11 import java.io.IOException JavaDoc;
12 import java.io.InputStream JavaDoc;
13 import java.io.InputStreamReader JavaDoc;
14 import java.io.ObjectInputStream JavaDoc;
15 import java.io.ObjectOutputStream JavaDoc;
16 import java.io.OutputStream JavaDoc;
17 import java.io.PrintStream JavaDoc;
18 import java.io.PrintWriter JavaDoc;
19 import java.net.URL JavaDoc;
20 import java.util.Iterator JavaDoc;
21
22 import org.apache.log4j.Logger;
23
24 /**
25  * Helper methods for working with File objects
26  *
27  *@author bconrad
28  *@created April 17, 2001
29  */

30 public class FileUtility {
31
32     protected static Logger log = Logger.getLogger(FileUtility.class);
33     
34     /**
35      * Return the contents of the provided File as a String
36      * @param file
37      * @return
38      */

39     public static String JavaDoc contentsOfFile(File JavaDoc file) {
40         String JavaDoc s = new String JavaDoc();
41         char[] buff = new char[50000];
42         InputStream JavaDoc is;
43         InputStreamReader JavaDoc reader;
44         try {
45             reader = new FileReader JavaDoc(file);
46             int nch;
47             while ((nch = reader.read(buff, 0, buff.length)) != -1) {
48                 s = s + new String JavaDoc(buff, 0, nch);
49             }
50         }
51         catch (java.io.IOException JavaDoc ex) {
52             s = null;
53         }
54         return s;
55     }
56
57
58     /**
59      * Return the contents of the provided file name as a String
60      *
61      * @param fileName
62      * @return
63      */

64     public static String JavaDoc contentsOfFile(String JavaDoc fileName) {
65         return contentsOfFile(new File JavaDoc(fileName));
66     }
67
68         /**
69      *
70      */

71     public static void copy(File JavaDoc inFile, File JavaDoc outFile) throws IOException JavaDoc {
72     
73         if (inFile.getCanonicalPath().equals(outFile.getCanonicalPath())) {
74             // inFile and outFile are the same,
75
// hence no copying is required
76
return;
77         }
78         FileInputStream JavaDoc fin = new FileInputStream JavaDoc(inFile);
79         FileOutputStream JavaDoc fout = new FileOutputStream JavaDoc(outFile);
80         copy(fin, fout);
81     }
82
83     /**
84      *
85      */

86     public static void copy(InputStream JavaDoc in, OutputStream JavaDoc out)
87         throws IOException JavaDoc
88          {
89     
90         synchronized (in) {
91             synchronized (out) {
92     
93                 byte[] buffer = new byte[256];
94                 try {
95                 while (true) {
96                     int bytesRead = in.read(buffer);
97                     if (bytesRead == -1)
98                         break;
99                     out.write(buffer, 0, bytesRead);
100                 }
101                 } catch(IOException JavaDoc e) {
102                     closeStreams(in,out);
103                     throw e;
104                 }
105             }
106             closeStreams(in,out);
107
108         }
109     
110     }
111
112     /**
113      * Close the provided input and output streams. Ignore any exception.
114      *
115      * @param inputStream
116      * @param outputStream
117      */

118     public static void closeStreams(InputStream JavaDoc inputStream, OutputStream JavaDoc outputStream) {
119         try {
120             inputStream.close();
121             outputStream.close();
122         } catch(Exception JavaDoc e) {
123         }
124     }
125
126
127     /**
128      * Ensure that the provided file exists. If it does not, create it along
129      * with any necessary directories in the path.
130      *
131      * @param file
132      * @return
133      */

134     public static boolean ensureFilePathExists(File JavaDoc file) {
135         File JavaDoc path;
136         try {
137             path = new File JavaDoc(file.getCanonicalPath());
138         }
139         catch (IOException JavaDoc e) {
140             log.debug("IOException on file " + file);
141             return false;
142         }
143         if (!path.exists()) {
144             File JavaDoc parent = new File JavaDoc(path.getParent());
145             log.debug("path does not exist, call self with parent " + parent);
146             ensurePathExists(parent);
147         }
148         return true;
149     }
150
151
152     /**
153      * Ensure that the path to the provided file exists. If it does not, create it.
154      *
155      * @param file
156      * @return
157      */

158     public static boolean ensurePathExists(File JavaDoc file) {
159         File JavaDoc path;
160         try {
161             path = new File JavaDoc(file.getCanonicalPath());
162         }
163         catch (IOException JavaDoc e) {
164             log.debug("IOException on file " + file);
165             return false;
166         }
167         if (!path.exists()) {
168             if (path.getParent() == null) {
169                 log.debug("Operation terminating. Unable to get parent for "+path.getAbsolutePath() );
170                 return false;
171             }
172             File JavaDoc parent = new File JavaDoc(path.getParent());
173             ensurePathExists(parent);
174             boolean result = path.mkdir();
175             log.debug("result "+result+" mkdir for " + path);
176             return result;
177         
178         }
179         return true;
180     }
181
182
183     /**
184      * Ensure that the provided file name exists. If it does not, create it along
185      * with any necessary directories in the path.
186      *
187      *
188      * @param fileString
189      * @return
190      */

191     public static boolean ensureFilePathExists(String JavaDoc fileString) {
192         return ensureFilePathExists(new File JavaDoc(fileString));
193     }
194
195
196     /**
197      * Ensure that the path to the provided file name exists. If it does not, create it.
198      * @param fileString
199      * @return
200      */

201     public static boolean ensurePathExists(String JavaDoc fileString) {
202         return ensurePathExists(new File JavaDoc(fileString));
203     }
204
205
206     public static PrintStream JavaDoc newPrintStreamOnFileNamed(File JavaDoc directory, String JavaDoc name) throws IOException JavaDoc {
207         File JavaDoc file = new File JavaDoc(directory, name);
208         log.debug("creating file " + name + " in " + directory.toString());
209         return new PrintStream JavaDoc(new FileOutputStream JavaDoc(file));
210     }
211
212
213     /**
214      * Create and return a PrintWriter for the provided directory and file name.
215      * @param directory
216      * @param name
217      * @return
218      * @throws IOException
219      */

220     public static PrintWriter JavaDoc newPrintWriterOnFileNamed(File JavaDoc directory, String JavaDoc name) throws IOException JavaDoc {
221         File JavaDoc file = new File JavaDoc(directory, name);
222         return new PrintWriter JavaDoc(new FileOutputStream JavaDoc(file));
223     }
224
225
226     /**
227      * Convert the provided File into a BufferedInputStream.
228      * Then read the stream and return the Object that was read.
229      *
230      * @param file
231      * @return
232      * @throws IOException
233      * @throws ClassNotFoundException
234      */

235     public static Object JavaDoc readObjectFromBufferedFileObject(File JavaDoc file) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
236         ObjectInputStream JavaDoc ois;
237         Object JavaDoc result = null;
238         log.debug("Opening input stream...");
239         FileInputStream JavaDoc fis = new FileInputStream JavaDoc(file);
240         BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(fis, 4096);
241         ois = new ObjectInputStream JavaDoc(bis);
242         log.debug("Reading serialized object from stream...");
243         result = ois.readObject();
244         return (result);
245     }
246
247
248     /**
249      * Read the provded file and return the contents as an Object.
250      *
251      *@param file java.lang.String
252      *@return java.lang.Object
253      *@exception IOException Description of Exception
254      *@exception ClassNotFoundException Description of Exception
255      */

256     public static Object JavaDoc readObjectFromFile(File JavaDoc file) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
257         log.debug("File " + file.toString());
258         return readObjectFromBufferedFileObject(file);
259     }
260
261
262     /**
263      * Read the contents of the provided file name residing in the provided directory.
264      * Return the contents as an Object.
265      *
266      *@param directory
267      *@param name
268      *@return java.lang.Object
269      *@exception IOException
270      *@exception ClassNotFoundException
271      */

272     public static Object JavaDoc readObjectFromFile(File JavaDoc directory, String JavaDoc name) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
273         File JavaDoc file;
274         file = new File JavaDoc(directory, name);
275         log.debug(directory.toString() + " " + name);
276         return readObjectFromBufferedFileObject(file);
277     }
278
279
280     /**
281      * Read the contents of the provided file name residing in the provided directory.
282      * Return the contents as an Object.
283      *
284      * @param fileWithPath
285      * @return
286      * @throws IOException
287      * @throws ClassNotFoundException
288      */

289     public static Object JavaDoc readObjectFromFileWithPath(String JavaDoc fileWithPath) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
290         return readObjectFromBufferedFileObject(new File JavaDoc(fileWithPath));
291     }
292
293
294     /**
295      * Redirect standard output to the log file.
296      */

297     public static void redirectStandardOutput() {
298         redirectStandardOutput(getLogFileName());
299     }
300
301
302     /**
303      * Redirect standard output to the provided File.
304      * @param file
305      */

306     public static void redirectStandardOutput(File JavaDoc file) {
307         try {
308             log.debug("redirectStandardOutput to " + file.getAbsolutePath());
309             PrintStream JavaDoc stdout = new PrintStream JavaDoc(new FileOutputStream JavaDoc(file));
310             System.setOut(stdout);
311         }
312         catch (Exception JavaDoc e) {
313             log.debug("Unable to redirect stdout to " + file.getAbsolutePath());
314         }
315     }
316
317
318     /**
319      * Redirect standard output to the provided file name.
320      * @param file
321      */

322     public static void redirectStandardOutput(String JavaDoc fileName) {
323         redirectStandardOutput(new File JavaDoc(fileName));
324     }
325
326
327     /**
328      * Return the contents of the provided file as a String.
329      * @param file
330      * @return
331      */

332     public static String JavaDoc stringFromFile(File JavaDoc file) {
333         return contentsOfFile(file);
334     }
335
336
337     /**
338      * Return the contents of the provided file name as a String.
339      * @param file
340      * @return
341      */

342     public static String JavaDoc stringFromFile(String JavaDoc fileName) {
343         return contentsOfFile(new File JavaDoc(fileName));
344     }
345
346
347     /**
348      * Convert the provided String into the provided File.
349      * @param string
350      * @param file
351      */

352     public static void stringToFile(String JavaDoc string, File JavaDoc file) {
353
354         try {
355             PrintWriter JavaDoc out = new PrintWriter JavaDoc(new FileWriter JavaDoc(file));
356             out.print(string);
357             out.close();
358         }
359         catch (FileNotFoundException JavaDoc fnfe) {
360             String JavaDoc msg = "File not found exception: " + file;
361         }
362         catch (IOException JavaDoc ioe) {
363             String JavaDoc msg = "IO Exception writing object output stream to file: " + file;
364         }
365     }
366
367
368     /**
369      * Convert the provided String into a File of the provided file name.
370      * @param string
371      * @param file
372      */

373     public static void stringToFile(String JavaDoc string, String JavaDoc fileString) {
374
375         stringToFile(string, new File JavaDoc(fileString));
376     }
377
378
379     /**
380      * Convert the provided String into the provided FileOutputStream.
381      * @param string
382      * @param fos
383      * @throws IOException
384      */

385     public static void stringToFileOutputStream(String JavaDoc string, FileOutputStream JavaDoc fos) throws IOException JavaDoc {
386         log.debug("");
387         fos.write(string.getBytes());
388     }
389
390
391     /**
392      * Write the provided object to a file of the provided directory and file name.
393      * @param object
394      * @param directory
395      * @param name
396      * @throws IOException
397      */

398     public static void writeObjectToFile(Object JavaDoc object, File JavaDoc directory, String JavaDoc name) throws IOException JavaDoc {
399         ObjectOutputStream JavaDoc oos;
400         File JavaDoc file;
401
402         log.debug("creating file " + name + " in " + directory.toString());
403         file = new File JavaDoc(directory, name);
404         writeObjectToFileObject(object, file);
405     }
406
407
408     /**
409      * Write the provided object to the provided File.
410      * @param object
411      * @param file
412      * @throws IOException
413      */

414     public static void writeObjectToFileObject(Object JavaDoc object, File JavaDoc file) throws IOException JavaDoc {
415         ObjectOutputStream JavaDoc oos = null;
416         log.debug("creating output stream on file...");
417         oos = new ObjectOutputStream JavaDoc(new FileOutputStream JavaDoc(file));
418         log.debug("writing object to stream...");
419         oos.writeObject(object);
420         log.debug("closing stream...");
421         oos.close();
422     }
423
424
425     /**
426      * Write the provided object to the provided file name.
427      * @param object
428      * @param fileAndPath
429      * @throws IOException
430      */

431     public static void writeObjectToFileWithPath(Object JavaDoc object, String JavaDoc fileAndPath) throws IOException JavaDoc {
432         writeObjectToFileObject(object, new File JavaDoc(fileAndPath));
433     }
434
435
436     /**
437      * Write the provided iterator to a file of the provided file name.
438      * @param it
439      * @param fileName
440      * @throws IOException
441      */

442     public static void iteratorToFile(Iterator JavaDoc it, String JavaDoc fileName) throws IOException JavaDoc {
443         log.debug("");
444         FileOutputStream JavaDoc stream = new FileOutputStream JavaDoc(fileName);
445         while (it.hasNext()) {
446             stringToFileOutputStream(it.next() + "\n", stream);
447         }
448
449     }
450
451
452     /**
453      * Return the provided File as a BufferedReader
454      * @param file
455      * @return
456      * @throws FileNotFoundException
457      */

458     public static java.io.BufferedReader JavaDoc getBufferedReaderFromFile(File JavaDoc file) throws FileNotFoundException JavaDoc {
459         BufferedReader JavaDoc bufferedReader = null;
460         FileReader JavaDoc frdr = new FileReader JavaDoc(file);
461         bufferedReader = new BufferedReader JavaDoc(frdr);
462         return bufferedReader;
463     }
464
465
466     /**
467      * Return the provided file name as a BufferedReader
468      * @param fileString
469      * @return
470      * @throws FileNotFoundException
471      */

472     public static java.io.BufferedReader JavaDoc getBufferedReaderFromFile(String JavaDoc fileString) throws FileNotFoundException JavaDoc {
473         return getBufferedReaderFromFile(new File JavaDoc(fileString));
474     }
475
476
477     public static String JavaDoc getExceptionMessage(Exception JavaDoc e, File JavaDoc file) {
478         return file.toString() + ": " + e.toString() + " Msg: " + e.getMessage();
479     }
480
481     /**
482      * Return the name of the log file.
483      * @return
484      */

485     public static String JavaDoc getLogFileName() {
486
487         // Create a new output stream for the standard output.
488
java.text.SimpleDateFormat JavaDoc formatter = new java.text.SimpleDateFormat JavaDoc("MMddyy.HHmmssSSS");
489         String JavaDoc fileName = null;//PropertyUtility.getBaseDirectory() + "/logs/." + formatter.format(new java.util.Date()) + ".log";
490

491         return fileName;
492     }
493     
494     /**
495      * Return a File for an existing file. If we can't find it by the fileName,
496      * find it in the classpath. If that fails, return null.
497      * @param fileName
498      * @return
499      */

500     public static File JavaDoc findExistingFile(String JavaDoc fileName) {
501         File JavaDoc file = null;
502         file = new File JavaDoc(fileName);
503         if (!file.exists()) {
504             file = null;
505             log.debug("find as resource");
506             URL JavaDoc url = FileUtility.class.getResource("/" + fileName);
507             if (url != null) {
508                 String JavaDoc urlFileName = url.getFile();
509                 file = new File JavaDoc(urlFileName);
510             }
511         }
512
513         if (file != null) {
514             log.debug("file "+file.getAbsolutePath()+" "+file.exists());
515         } else {
516             log.debug("file null");
517         }
518         return file;
519     }
520
521     /**
522      * Return the provided InputStream as a String
523      * @param inputStream
524      * @return
525      */

526     public static String JavaDoc streamToString(InputStream JavaDoc inputStream) {
527         String JavaDoc s = new String JavaDoc();
528         char[] buff = new char[50000];
529         try {
530             InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(inputStream);
531             int nch;
532             while ((nch = reader.read(buff, 0, buff.length)) != -1) {
533                 s = s + new String JavaDoc(buff, 0, nch);
534             }
535         }
536         catch (java.io.IOException JavaDoc ex) {
537             s = null;
538         }
539         return s;
540     }
541
542 }
543
Popular Tags