KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > incava > io > FileExt


1 package org.incava.io;
2
3 import java.io.*;
4 import java.util.Vector JavaDoc;
5
6
7 public class FileExt
8 {
9     /**
10      * Reads the file into a single string, which is null on error. The returned
11      * string will contain end-of-line characters. The <code>arg</code> argument
12      * is just so we can overload based on return type.
13      */

14     public static String JavaDoc readFile(String JavaDoc fileName, String JavaDoc arg)
15     {
16         return readFile(new File(fileName), arg);
17     }
18
19     /**
20      * Reads the file into a string array, without end-of-line characters
21      * (sequences). The array is null on error. The <code>arg</code> argument is
22      * just so we can overload based on return type.
23      */

24     public static String JavaDoc[] readFile(String JavaDoc fileName, String JavaDoc[] arg)
25     {
26         return readFile(new File(fileName), arg);
27     }
28
29     /**
30      * Reads the file into a single string, which is null on error.The
31      * <code>arg</code> argument is just so we can overload based on return
32      * type.
33      */

34     public static String JavaDoc readFile(File file, String JavaDoc arg)
35     {
36         String JavaDoc[] contents = readFile(file, new String JavaDoc[] {});
37         if (contents == null) {
38             return null;
39         }
40         else {
41             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
42             String JavaDoc lineSep = System.getProperty("line.separator");
43             
44             for (int i = 0; contents != null && i < contents.length; ++i) {
45                 buf.append(contents[i] + lineSep);
46             }
47             
48             return buf.toString();
49         }
50     }
51
52     /**
53      * Reads the file into a string array, without end-of-line characters
54      * (sequences). The <code>arg</code> argument is just so we can overload
55      * based on return type.
56      */

57     public static String JavaDoc[] readFile(File file, String JavaDoc[] arg)
58     {
59         try {
60             BufferedReader br = new BufferedReader(new FileReader(file));
61             Vector JavaDoc vec = new Vector JavaDoc();
62
63             String JavaDoc in;
64             while ((in = br.readLine()) != null) {
65                 // contents.append(in + System.getProperty("line.separator"));
66
vec.addElement(in);
67             }
68
69             return (String JavaDoc[])vec.toArray(new String JavaDoc[] {});
70         }
71         catch (Exception JavaDoc e) {
72             tr.Ace.log("exception: " + e);
73             return null;
74         }
75     }
76
77 }
78
Popular Tags