package com.hu; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; /* * 读入123.txt文本 * 判断一个文件的每个文字出现次数 * * */ public class jiexi { public static void main(String[] args) throws IOException {
//创建StringBUilder用来存放所有字节 StringBuilder sb= new StringBuilder();
//创建输入流 BufferedReader bufferedReader = new BufferedReader(new FileReader("123.txt")); String lin; while ((lin = bufferedReader.readLine()) != null) {
//添加 sb.append(lin); }
//关流 bufferedReader.close();
//调用方法jiexi1 HashMap<Character, Integer> characterIntegerHashMap = jiexi1(sb); //遍历characterIntegerHashMap集合 Set<Map.Entry<Character, Integer>> keys = characterIntegerHashMap.entrySet();
//创建计数count int count=0; for (Map.Entry<Character, Integer> key : keys) {
//输出集合中的内容 System.out.print(key.getKey()+"---"+key.getValue()+" ");
count++;
//换行 if (count==10){ System.out.println(); count=0; } } } public static HashMap<Character, Integer> jiexi1(StringBuilder sb) {
//创建一个以字符为键,以数字为值的map集合 Map<Character, Integer> map = new HashMap<>();
//遍历传来的sb for (int i=0;i<sb.length();i++) {
//以char格式接收sb char c = sb.charAt(i);
//判断map集合中的键和当前字符是否存在 if ((map.containsKey(c)) != false) {
//遍历map Set<Map.Entry<Character, Integer>> entries = map.entrySet(); for (Map.Entry<Character, Integer> entry : entries) {
//获取当前键和值 Character key = entry.getKey(); Integer value = entry.getValue();
//创建记录变量 int count=value;
//比较当前map的键和当前字符是否相等 if (key.equals(c)){
//相等加1 count++; map.put(c,count); } }
//如果不相等给这个字符初始化为出现一次 }else { map.put(c,1); } }
//返回map集合 return (HashMap<Character, Integer>) map; } }