-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandler.java
More file actions
100 lines (85 loc) · 3.97 KB
/
FileHandler.java
File metadata and controls
100 lines (85 loc) · 3.97 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/**
* This class encapsulates some static method used for file reading and writing.
* @author Michael
*
*/
public class FileHandler {
private FileHandler(){}
public static String readFile(String url, boolean withLineWrap){
String result = "";
try {
FileReader fr = new FileReader(url);
BufferedReader br = new BufferedReader(fr);
String temp = null;
if ( withLineWrap ) {
while ( ( temp=br.readLine() ) !=null ){
result += (temp+"\n");
}
}
else {
while ( ( temp=br.readLine() ) !=null ){
result += temp;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void writeFile(String url, String text, boolean withLineWrap){
try {
FileWriter fw = new FileWriter(url);
BufferedWriter bw = new BufferedWriter(fw);
char[] str = text.toCharArray();
for ( int i=0; i<str.length; i++ ) {
if ( withLineWrap && i%100==0 && i!=0 )
bw.append('\n');
bw.append(str[i]);
}
bw.close();
fw.close();
System.out.println("Writing file completed!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void writeSymbolToFile(String url, ArrayList<Symbol> symbolList) {
// TODO Auto-generated method stub
try {
FileWriter fw = new FileWriter(url);
BufferedWriter bw = new BufferedWriter(fw);
for ( Symbol s: symbolList ){
/**
* 由于换行符和空格没法表示,所以我就用了这么一个方法,对它们进行特殊处理
*/
if ( s.letter.equals("\n") ) {
bw.write( "lineWrapper" + " " + s.probability + " " + s.low + " " + s.high );
}
else if ( s.letter.equals(" ") ){
bw.write( "space" + " " + s.probability + " " + s.low + " " + s.high );
} else {
bw.write( s.letter + " " + s.probability + " " + s.low + " " + s.high );
}
bw.newLine();
}
bw.close();
fw.close();
System.out.println("Writing file completed!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}