文本内容排序输出
如果向文本中用filewrite中的write方法写入 "张二 8
王三 4
李四 5 "三行数据,如何读出的顺序为 "王三 4
李四 5
张二 8 ".急需帮助,在这先谢谢了!
------解决方案--------------------张二 8
王三 4
李四 5
青书 10
亮亮 1
import java.io.*;
import java.util.*;
class testFileSort{
public static void main(String []args){
BufferedReader input=null;
Set <Person> s=new TreeSet <Person> (new PersonComparator());
try{
input=new BufferedReader(new FileReader( "d:/data.txt "));
String buf;
while((buf=input.readLine())!=null){
String name=null;
int num=0;
StringTokenizer st=new StringTokenizer(buf);
while(st.hasMoreTokens()){
name = st.nextToken();
num = Integer.parseInt(st.nextToken());
}
s.add(new Person(name,num));
}
}catch(
FileNotFoundException e){
System.out.println( "Can 't find the file!!! ");
}catch(
IOException e){
e.printStackTrace();
}finally{
if(input!=null){
try{
input.close();
}catch(IOException e){}
}
}
Iterator <Person> it=s.iterator();
for(int i=0;i <s.size();i++){
System.out.println(it.next());
}
}
}
class Person{
private String name;
private int num;
public Person(String n,int num){
name=n;
this.num=num;
}
public int getNum(){
return num;
}
public String toString(){
return "Name: "+name+ " Num: "+num;
}
}
class PersonComparator implements Comparator <Person> {
public int compare(Person o1,Person o2){
return o1.getNum()-o2.getNum();
}
}