天天看點

IO應用——讀取文本檔案并統計單詞個數

讀取一共文本檔案,統計出其中每一個單詞出現的次數,并把結果儲存在另外的一個檔案中

此處我的文本内容是:i love you,i love you

我就沒有儲存到另一個檔案了,要儲存直接用輸出流就行了

public static void main(String[] args) throws IOException {
		Reader reader = new FileReader("C:/Users/maple/Desktop/itsourcejava/xx/d.txt");
		Map<String, Integer> map = new HashMap<>();
		//正則不會寫,隻能寫成這樣了
		//所有非字母出現一次或多次
		String regex = "[^a-zA-z]+";
		int n;
		//此處有bug,如果此數組長度寫小了,結果就不一樣
		char[] ch = new char[1024];
		while ((n = reader.read(ch)) != -1) {
			String string = new String(ch, 0, n);
			String[] split = string.split(regex);
			for (String s : split) {
				if (s.length()>=1) {
					if (map.containsKey(s))
						map.put(s, map.get(s)+1);
					 else 
						map.put(s, 1);
				}
			}
		}
		
		System.out.println(map);
		
	}
           

結果:

{love=2, i=2, you=2}