java统计文件中每个单词出现的次数

public class WordNum {
	public static void wordNum() throws IOException{
		FileReader fr=new FileReader("3.txt");
		HashMap<String,Integer> map=new HashMap<>();
		int len;
		int i=0;
		String[] str =null;
		char[] ch=new char[1024];
		while((len=fr.read(ch))!=-1){
			String s=new String(ch,0,len);
			//以非单词字符截取
			str=s.split("\\W+");
		}
		//判断单词单词是否重复
		for(String s:str){
			if(map.containsKey(s)){
				map.put(s, ++i);
			}else{
				map.put(s, i);
			}
		}
		
		//获得所有的键
		Set<String> set=map.keySet();
		for(String ss:set){
			System.out.println(ss+"出现:"+map.get(ss)+"次");
		}
		
	}
}

public class WordTest {
	public static void main(String[] args) throws IOException {
		WordNum.wordNum();
	}
}

你可能感兴趣的:(Java,java,字符串)