日期:2014-05-20 浏览次数:20985 次
package com.monitor1394.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author monitor * Created on 2011-1-6, 23:30:52 */ public class NameSort { public NameSort(){ } /** * 从文件中获得名字列表 * @param file 存名字的文件 * @return 名字列表 * @throws FileNotFoundException * @throws IOException */ public static List<String> getNameList(String file) throws FileNotFoundException, IOException{ List<String> nameList=new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(file)); String name=null; while((name=br.readLine())!=null){ nameList.add(name); System.out.println(name); } if(br!=null)br.close(); return nameList; } /** * 将名字写到指定文件 * @param nameList 名字列表 * @param file 指定文件 * @throws IOException 文件操作异常 */ public static void exportNameToFile(List<String>nameList,String file) throws IOException{ BufferedWriter bw = new BufferedWriter(new FileWriter(file)); for(String name:nameList){ bw.write(name); bw.newLine(); } bw.flush(); bw.close(); } public static void main(String[] args){ try { List<String> nameList = getNameList("test.txt"); //排序 Collections.sort(nameList); exportNameToFile(nameList,"name.txt"); } catch (FileNotFoundException ex) { Logger.getLogger(NameSort.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(NameSort.class.getName()).log(Level.SEVERE, null, ex); } } }
------解决方案--------------------
下面是我请两天写的名字排序的例子(统计同学的通讯方式时用的),名字排序我们一般是按拼音,但是你调用 Collections.sort(nameList);来排序汉字的话就不是那个顺序,我又给名字加了个拼音,排序的时候根据拼音来排:
package com.monitor1394.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; class Name implements Comparable{ private String name; private String spell; public Name(String name,String spell){ this.name=name; this.spell=spell; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSpell() { return spell; } public void setSpell(String spell) { this.spell = spell; } public int compareTo(Object o) { if(o instanceof Name){ Name n=(Name)o; return spell.compareTo(n.getSpell()); }else{ return 1; } } } public class Test { public static void main(String[] args) { List<Name> nameList=new ArrayList<Name>(); nameList.add(new Name("邓永枢","dengys")); nameList.add(new Name("陈济民","chenjm")); nameList.add(new Name("方镇云","fangzy")); nameList.add(new Name("刘彪","liub")); nameList.add(new Name("叶攀","yep")); nameList.add(new Name("劳高津","laogj")); nameList.add(new Name("黄品","huangp")); nameList.add(new Name("黄高栋","huanghgd")); nameList.add(new Name("温生文","wensm")); //...... Collections.sort(nameList); for(Name name:nameList){ System.out.println(name.getName()); } } }