- /**获取一个文本上每个字符出现的次数,将结果写在times.txt上*/
- BufferedReader br = new BufferedReader(new FileReader("exercise.txt"));
- HashMap<Character,Integer> hm = new HashMap<>();
- int b;
- while((b=br.read())!=-1){
- char c =(char)b;
- hm.put(c,!hm.containsKey(c)?1:hm.get(c)+1);
- }
- br.close();
-
- BufferedWriter bw = new BufferedWriter(new FileWriter("times.txt"));
- for(char c:hm.keySet()){
- switch(c){
- case '\t':
- bw.write("\\t"+"("+hm.get(c)+")");
- break;
- case '\r':
- bw.write("\\r"+"("+hm.get(c)+")");
- break;
- case '\n':
- bw.write("\\n"+"("+hm.get(c)+")");
- break;
- default:
- bw.write(c+"("+hm.get(c)+")");
- break;
- }
- bw.newLine();
- }
- bw.close();
复制代码 |
|