public static void main2(String[] args) {
String path = MapUtil.class.getClassLoader().getSystemResource("word.txt").toString().substring(6);
System.out.println(path);
//<单词, 数量>
Map<String, Integer> map = new HashMap<String, Integer>();
String line;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(path));
while (null != (line=bufferedReader.readLine())) {
String[] words = line.split("\\s+");
for(String word :words){
if (map.containsKey(word)) {
map.put(word, map.get(word)+1);
}else {
map.put(word, 1);
}
}
}
Set<String> wordSets = map.keySet();
for(String key : wordSets){
System.out.println(key + "有:" + map.get(key) + "个.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
读取并输出一个文件中单词数量(java)
最新推荐文章于 2024-02-28 21:02:51 发布