KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > util > TextFile


1 package hudson.util;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileInputStream JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.io.InputStreamReader JavaDoc;
8 import java.io.PrintWriter JavaDoc;
9 import java.io.StringWriter JavaDoc;
10
11 /**
12  * Represents a text file.
13  *
14  * Provides convenience methods for reading and writing to it.
15  *
16  * @author Kohsuke Kawaguchi
17  */

18 public class TextFile {
19     private final File JavaDoc file;
20
21     public TextFile(File JavaDoc file) {
22         this.file = file;
23     }
24
25     public boolean exists() {
26         return file.exists();
27     }
28
29     /**
30      * Reads the entire contents and returns it.
31      */

32     public String JavaDoc read() throws IOException JavaDoc {
33         StringWriter JavaDoc out = new StringWriter JavaDoc();
34         PrintWriter JavaDoc w = new PrintWriter JavaDoc(out);
35         BufferedReader JavaDoc in = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(new FileInputStream JavaDoc(file),"UTF-8"));
36         try {
37             String JavaDoc line;
38             while((line=in.readLine())!=null)
39                 w.println(line);
40         } finally{
41             in.close();
42         }
43         return out.toString();
44     }
45
46     /**
47      * Overwrites the file by the given string.
48      */

49     public void write(String JavaDoc text) throws IOException JavaDoc {
50         AtomicFileWriter w = new AtomicFileWriter(file);
51         w.write(text);
52         w.commit();
53     }
54
55     public String JavaDoc readTrim() throws IOException JavaDoc {
56         return read().trim();
57     }
58
59     public String JavaDoc toString() {
60         return file.toString();
61     }
62 }
63
Popular Tags