参考网上的代码,自己再略微修改,纯作记录
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class readFile { public static void main(String[] args) { int lineNum = 0;//定义变量 行数 HashMap<String,Integer> map = new HashMap<String ,Integer>();//定义map,用于保存文本中的单词和出现次数 BufferedReader in = null; try { in = new BufferedReader(new FileReader("F:\\EC.txt"));//文本地址 String buffer = null; // while((buffer = in.readLine()) != null) { lineNum++; String[] words = buffer.replaceAll("[^a-zA-Z]+", " ").trim().split(" ");//正则表达式分割 for(int i = 0; i < words.length; i++) { map.put(words[i],map.getOrDefault(words[i], 0)+1);//value默认为0,每重复1次加1 } } //本段为输出map中保存的数据 Set<Map.Entry<String,Integer>> set = map.entrySet(); for(Iterator<Map.Entry<String,Integer>> it = set.iterator();it.hasNext();) { Map.Entry<String,Integer> entr = (Map.Entry<String,Integer>)it.next(); System.out.println(entr.getKey()+"--------"+entr.getValue()); } System.out.println("行数"+lineNum); System.out.println("字数"+map.size()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { in.close();//关闭缓冲字符流 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
时间: 2024-10-11 05:20:14