-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteTextFile.java
More file actions
55 lines (48 loc) · 1.29 KB
/
Copy pathReadWriteTextFile.java
File metadata and controls
55 lines (48 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.io.*;
import java.util.Scanner;
/**
* Read and write a file using an explicit encoding.
* Removing the encoding from this code will simply cause the
* system's default encoding to be used instead.
*/
public final class ReadWriteTextFile {
// PRIVATE
private final String fFileName;
private final String fEncoding;
/** Constructor. */
ReadWriteTextFile(String aFileName){
fEncoding = "UTF-8";
fFileName = aFileName;
}
/** Write fixed content to the given file. */
void write(String content) throws IOException {
log("Writing to file named " + fFileName + ". Encoding: " + fEncoding);
Writer out = new OutputStreamWriter(new FileOutputStream(fFileName), fEncoding);
try {
out.write(content);
}
finally {
out.close();
}
}
/** Read the contents of the given file. */
String read() throws IOException {
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
try {
while (scanner.hasNextLine()){
text.append(scanner.nextLine() + NL);
}
}
finally{
scanner.close();
}
log("Text read in: " + text);
return text.toString();
}
private void log(String aMessage){
System.out.println(aMessage);
}
}