题目:编写一个程序,统计一个文本文件所包含的不同单词的个数,并将结果保存在另一个文件中。输出文件的格式为:每个单词占用一行,其内容包括单词本身及其出现的次数;各单词之间要按照从小到大的顺序排列。
import java.io.*; import java.util.*; public class Text7 { static ArrayList<String> wordList = new ArrayList<String>(); public static void main(String[] args)throws FileNotFoundException{ //读入"word.txt"内容并存进字符串中 Scanner input = new Scanner(new File("word.txt")); String s = input.nextLine(); //分割字符串并存进字符串数组中 String [] strArr = s.split(" "); HashMap<String,Integer> hashMap = new HashMap<String,Integer>(); //遍历字符串数组 for(String word:strArr){ //求出不同单词个数 if(!wordList.contains(word.toLowerCase())){ wordList.add(word.toLowerCase()); } //求出每一个单词出现的个数 Integer currentCount = hashMap.get(word); if(currentCount == null){ currentCount = 0; } hashMap.put(word,++currentCount); } System.out.println("不同单词个数为:" + wordList.size()); //创建新文件"newDemo2.txt"并将"排序单词出现次数"等内容存进新文件中 try{ FileOutputStream fos = new FileOutputStream("newDemo2.txt",false); fos.write(sort(hashMap).getBytes()); fos.close();//关闭文件流 }catch(IOException ex){ System.out.println("无法打开文件!"); } } //将"hashMap"中的“value”值进行排序 public static String sort(Map<String,Integer> hashMap){ String str = "不同单词个数为:" + wordList.size() + "\r\n"; List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(hashMap.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { if (o1.getValue() < o2.getValue()) return -1; else if (o1.getValue() > o2.getValue()) return 1; return 0; } }); //打印信息 for (int i = 0; i < list.size(); i++) { java.util.Map.Entry<String, Integer> id = list.get(i); str += "单词:" + id.getKey() + " 出现次数:" + id.getValue() + "\r\n"; } return str; } }
原文本"word.txt"内容:
程序运行成功后创建的"newDemo2.txt"文本: