public static void readFile(String fileName, String fielLocation) throws IOException { File file = new File(fileName); FileReader fileReader = new FileReader(file); BufferedReader input = new BufferedReader(fileReader);
String text = ""; Map<String,Integer> map = new HashMap<String,Integer>();//统计用Map
while ((text = input.readLine()) != null) {//读取文件
String [] words = text.split(" ");//得到每一行的单词数组
for(int i = 0; i < words.length; i ++) { String key = words[i].trim().toString(); if(map.containsKey(key)) map.put(key, map.get(key) + 1);//同样的单词计数+1 else map.put(key, 1);//出现第一次 计数置1 } }
TreeMap treeMap = new TreeMap(map);//对统计用Map进行重构,因为Value是Integer,默认按自然神排序
for(int i = 0; i < 10; i ++) {//输出单词数最多的10个单词 System.out.println(treeMap.get(treeMap.lastKey())); //输出当前最大值 treeMap.remove(treeMap.lastKey());//去掉当前最大值 } }
使用 java.text.BreakIterator 、java.util.TreeMap
public static void readFile(String fileName, String fielLocation) throws IOException { File file = new File(fileName);
FileReader fileReader = new FileReader(file);
BufferedReader input = new BufferedReader(fileReader);
String text = "";
Map<String,Integer> map = new HashMap<String,Integer>();//统计用Map
while ((text = input.readLine()) != null) {//读取文件
String [] words = text.split(" ");//得到每一行的单词数组
for(int i = 0; i < words.length; i ++) {
String key = words[i].trim().toString();
if(map.containsKey(key))
map.put(key, map.get(key) + 1);//同样的单词计数+1
else
map.put(key, 1);//出现第一次 计数置1
}
}
TreeMap treeMap = new TreeMap(map);//对统计用Map进行重构,因为Value是Integer,默认按自然神排序
for(int i = 0; i < 10; i ++) {//输出单词数最多的10个单词
System.out.println(treeMap.get(treeMap.lastKey())); //输出当前最大值
treeMap.remove(treeMap.lastKey());//去掉当前最大值
}
}