packagecom.swift;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.util.ArrayList;importjava.util.Collections;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importjava.util.Map.Entry;importjava.util.TreeMap;importorg.apache.poi.hwpf.HWPFDocument;importorg.apache.poi.xwpf.extractor.XWPFWordExtractor;importorg.apache.poi.xwpf.usermodel.XWPFDocument;public classIO_Sort_Select {public static void main(String[] args) throwsIOException {/** 从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序*/File file_s= new File("e:\\neck\\data.doc");
File dir= new File("e:\\neck");if (!dir.exists() &&dir.isDirectory()) {
System.out.println("目录不存在,即将创建...");
dir.mkdirs();
}
List list = new ArrayList();
String text=readFromDoc(file_s);
String[] hang= text.split("\\r");for (int i = 0; i < hang.length; i++) {
System.out.println(hang.length);
System.out.println(hang[i]);
String[] lie= hang[i].split("\\,");for (int j = 0; j < lie.length; j++) {if (j == 1) {
list.add(lie[j]);
}
}
}
printList(list);
Map map = new TreeMap();for(String str : list) {
map.put(str,0);
}for(String str:list) {if(map.containsKey(str)) {int num=map.get(str);
num++;
map.remove(str);
map.put(str, num);
}
}
List> listMap=new ArrayList>(map.entrySet());
Collections.sort(listMap,new Comparator>(){
@Overridepublic int compare(Entry arg0, Entryarg1) {int num=arg1.getValue()-arg0.getValue();return num==0?arg0.getKey().compareTo(arg1.getKey()):num;
}
});for(Entryentry:listMap) {
System.out.println("重复的姓名是 :"+entry.getKey()+" 重复的次数是:"+entry.getValue());
}
}private static void printList(Listlist) {for(String str : list) {
System.out.println(str);
}
}public static String readFromDocx(File file) throwsIOException {
FileInputStream fis= newFileInputStream(file);
XWPFDocument docx= newXWPFDocument(fis);
XWPFWordExtractor extractor= newXWPFWordExtractor(docx);
String text=extractor.getText();returntext;
}public static String readFromDoc(File file) throwsIOException {
FileInputStream fis= newFileInputStream(file);
HWPFDocument doc= newHWPFDocument(fis);
String text=doc.getDocumentText();returntext;
}
}