-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCharCountTest.java
More file actions
79 lines (69 loc) · 2.21 KB
/
Copy pathCharCountTest.java
File metadata and controls
79 lines (69 loc) · 2.21 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
package tutorial.java;
import org.junit.Test;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class CharCountTest {
@Test
public void test(){
FileReader fr = null;
BufferedWriter bw = null;
try {
Map<Character, Integer> map = new HashMap<>();
fr = new FileReader("test.txt");
int c = 0;
while( (c = fr.read()) != -1){
char ch = (char) c;
if(map.get(ch) == null){
map.put(ch, 1);
}else{
map.put(ch, map.get(ch) +1 );
}
}
bw = new BufferedWriter(new FileWriter("charCount.txt"));
// 遍历Map, 再写入数据
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
for( Map.Entry<Character, Integer> entry : entrySet){
switch (entry.getKey()){
case ' ':
bw.write("space: "+ entry.getValue());
break;
case '\r':
bw.write("enter: "+ entry.getValue());
break;
case '\n':
bw.write("newLine: "+ entry.getValue());
break;
case '\t':
bw.write("tab: "+ entry.getValue());
break;
default:
bw.write( entry.getKey() + "= "+ entry.getValue());
break;
}
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fr != null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}