日期:2014-05-20 浏览次数:21237 次
package csdn;
import java.io.*;
import java.util.*;
public class CountWords {
public static void main(String[] a) {
InnerCountWords icw = new InnerCountWords("words.txt");
Map<String,Integer> result = icw.getResult(); //开始统计
System.out.println(result);
}
}
class InnerCountWords {
private String fileName;
public InnerCountWords(String fileName) {
this.fileName = fileName;
}
public Map<String,Integer> getResult() {
Map<String,Integer> result = new HashMap<String,Integer>();
FileInputStream fis = null;
try {
fis = new FileInputStream(fileName); //打开文件
int in = 0; //读入的字符
StringBuffer sb = new StringBuffer(); //缓存单词
in = fis.read(); //读入
boolean notEnd = true; //是否是文件尾
while(notEnd) {
if(-1 == in) {
notEnd = false; //如果到文件尾,结束while
}
if(Character.isLetter((char)in)) {
sb.append((char)in); //判断读入的是否是字母,如果是,就追加到StringBuffer
} else {
//否则就判断StringBuffer里面是否有单词存在,如果有就加入到Map中
if(sb.length() > 0) {
if(result.containsKey(sb.toString())) {
result.put(sb.toString(), result.get(sb.toString()) + 1);
} else {
result.put(sb.toString(),1);
}
}
sb = new StringBuffer(); //重新设置StringBuffer
}
in = fis.read(); //读入字符
}
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}