你运行看看:
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileWriter;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- import java.util.Scanner;
-
- public class $ {
-
- private static List<Person> data = new ArrayList<Person>();
-
- public static void main(String... _) throws Exception {
-
- Scanner in = null;
- try {
- in = new Scanner(new File("D:/a.txt"));
-
- while (in.hasNextLine()) {
- String str = in.nextLine();
- String[] arr = str.split(" ");// 注意txt里面两列之间需有个空格
- data.add(new Person(arr[0], toInt(arr[1])));
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } finally {
- if (in != null) {
- in.close();
- }
- }
-
- System.out.println("pai xu qian:" + data);
-
- Collections.sort(data, new Comparator<Person>() {
-
- public int compare(Person o1, Person o2) {
-
- // 按年龄升序
- return o1.getAge() - o2.getAge();
-
- // 按年龄降序
- // return o2.getAge() - o1.getAge();
- }
- });
- System.out.println("pai xu hou:" + data);
-
- FileWriter fw = new FileWriter(new File("D:/b.txt"));
- for (Person p : data) {
- fw.write(p.getName() + " " + p.getAge() + "\r\n");
- }
- fw.flush();
- fw.close();
-
- System.out.println("已经保存到D:/b.txt");
- }
-
- private static int toInt(String str) {
- try {
- return Integer.parseInt(str);
- } catch (Exception e) {
- return 0;
- }
- }
- }
-
- class Person {
- private String name;
- private int age;
-
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String toString() {
- return "{" + name + "," + age + "}";
- }
- }
复制代码 |