1
2
3
4
5
6
7
8 package it.imolinfo.jbi4corba.jbi.component;
9
10 import it.imolinfo.jbi4corba.Logger;
11 import it.imolinfo.jbi4corba.LoggerFactory;
12 import it.imolinfo.jbi4corba.jbi.Messages;
13
14 import java.io.BufferedReader;
15 import java.io.BufferedWriter;
16 import java.io.File;
17 import java.io.FileNotFoundException;
18 import java.io.FileReader;
19 import java.io.FileWriter;
20 import java.io.IOException;
21 import java.io.Writer;
22
23
24
25
26
27 public class ReadWriteTextFile {
28
29
30 private static final Logger LOG =
31 LoggerFactory.getLogger(ReadWriteTextFile.class);
32 private static final Messages MESSAGES =
33 Messages.getMessages(ReadWriteTextFile.class);
34
35
36
37
38
39
40
41
42 static public String getContents(File aFile) {
43
44
45 StringBuffer contents = new StringBuffer();
46
47
48 BufferedReader input = null;
49 try {
50
51
52 input = new BufferedReader(new FileReader(aFile));
53 String line = null;
54
55
56
57
58
59 while ((line = input.readLine()) != null) {
60 contents.append(line);
61 contents.append(System.getProperty("line.separator"));
62 }
63 } catch (FileNotFoundException ex) {
64 ex.printStackTrace();
65 } catch (IOException ex) {
66 ex.printStackTrace();
67 } finally {
68 try {
69 if (input != null) {
70
71
72 input.close();
73 }
74 } catch (IOException ex) {
75 ex.printStackTrace();
76 }
77 }
78 return contents.toString();
79 }
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 static public void setContents(File aFile, String aContents)
97 throws FileNotFoundException, IOException {
98 if (aFile == null) {
99 String msg=MESSAGES.getString("CRB000226_File_should_not_be_null");
100 LOG.error(msg);
101 throw new IllegalArgumentException(msg);
102
103 }
104 if (!aFile.exists()) {
105 String msg=MESSAGES.getString("CRB000227_File_does_not_exist", new Object[] {aFile});
106 LOG.error(msg);
107 throw new FileNotFoundException(msg);
108 }
109 if (!aFile.isFile()) {
110 String msg=MESSAGES.getString("CRB000228_Should_not_be_a_directory", new Object[] {aFile});
111 LOG.error(msg);
112 throw new IllegalArgumentException(msg);
113 }
114 if (!aFile.canWrite()) {
115 String msg=MESSAGES.getString("CRB000229_File_cannot_be_written", new Object[] {aFile});
116 LOG.error(msg);
117 throw new IllegalArgumentException(msg);
118 }
119
120
121
122 Writer output = null;
123 try {
124
125
126 output = new BufferedWriter(new FileWriter(aFile));
127 output.write(aContents);
128 } finally {
129
130 if (output != null)
131 output.close();
132 }
133 }
134
135
136
137
138 public static void main(String... aArguments) throws IOException {
139 File testFile = new File("/tmp/blah.txt");
140 LOG.debug("Original file contents: " + getContents(testFile));
141 setContents(testFile, "Gopalan says hello.");
142 LOG.debug("New file contents: " + getContents(testFile));
143 }
144 }