java中获取文本上每个字符出现的次数
/获取文本上每个字符出现的次数 提示:遍历文本的每一个字符;字符及出现的次数保存在Map中;将Map中数据 写入文件/
package IO;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class exercise1 {
@Test
public void testWordCount(){
FileReader fr=null;
BufferedWriter bw=null;
try {
Map<Character, Integer> map = new HashMap<>();
fr = new FileReader("hello.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("count.txt"));
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
for(Map.Entry<Character,Integer> entry:entrySet){
switch (entry.getKey()){
case' ':
bw.write("空格="+entry.getValue());
break;
case'\t':
bw.write("tab键="+entry.getValue());
break;
case'\r':
bw.write("回车="+entry.getValue());
break;
case'\n':
bw.write("回车="+entry.getValue());
break;
default:
bw.write(entry.getKey()+"="+entry.getValue());
break;
}
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|