题目:文件intel.txt,内容如下:
小王【空格】10000【回车】
小强【空格】12345【回车】
小张【空格】2342 【回车】
小强【空格】1030 【回车】
小周【空格】1020 【回车】
请编写一程序从test.txt中读取数据,并按数字大小排序后写入另一文件sun.txt(写入格式同上)
package com.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test3 {
public static void main(String[] args) {
//read
try {
List<Person> persons = new ArrayList<Person>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("e://test.txt"),"Utf-8"));
String line = null;
while((line = in.readLine())!= null){
String[] temp = line.split(" ");
persons.add(new Person(Integer.valueOf(temp[1]),temp[0]));
}
in.close();
//sort
Collections.sort(persons, new Comparator<Person>() {
public int compare(Person o1, Person o2){
return o1.getId().compareTo(o2.getId());
}
});
//write
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("e:/sun.txt"), "UTF-8"));
for(Person person : persons){
String s = person.getName() + " " + person.getId();
System.out.println(s);
out.write(s+"\r\n");
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Person{
Integer id;
String name;
public Person(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}