读取一共文本文件,统计出其中每一个单词出现的次数,并把结果保存在另外的一个文件中
此处我的文本内容是: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}