- package come.heima.fuxi;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.util.HashMap;
- public class Demo3 {
- /**
- * 统计一个文本文件中出现的字符次数,结果存到另外一个文本中.
- */
- public static void main(String[] args) throws Exception {
- BufferedReader br = new BufferedReader(new FileReader("a.txt"));
- BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
- HashMap<Character, Integer> hm = new HashMap<>();
- String len;
- while((len = br.readLine())!= null){
- char[] ch = len.toCharArray();
- for (char c : ch) {
- if(!hm.containsKey(c)){
- hm.put(c, 1);
- }else{
- hm.put(c, (hm.get(c)+1));
- }
- }
- }
- for (Character c1 : hm.keySet()) {
- Integer sum = hm.get(c1);
- bw.write(c1.toString() + sum + "次");
- bw.newLine();
- }
- br.close();
- bw.close();
- }
-
- }
复制代码
我们群有人吧这题晒出来了,正好看见了,赚点金币学习下 |