java读取文本从大到小排序写出 高分悬赏,30分钟有完整答案的送1000财富

文件1.in为某公司员工的业绩得分表,包含姓名、性别、年龄和业绩得分4列,列与列之间的内容用空格符隔开。请设计一个程序,将该表的内容按业绩得分从高到低排序,然后将结果输出到1.out文件中。1.in 姓名 性别 年龄 业绩得分
测试1 男 27 95
测试2 男 25 86.5
测试3 女 25 88
测试4 男 28 93.5
测试5 女 23 72
测试6 男 20 99.5
测试7 男 22 77
测试8 女 26 68.5

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class T {

  public static void main(String[] args) throws IOException {
    String inFile = "D:/1.in";
    String outFile = "D:/1.out";
    List<Student> students = readStudents(inFile);
    Collections.sort(students);
    writeStudents(outFile, students);
  }

  private static void writeStudents(String file, List<Student> students)
      throws IOException {
    File f = new File(file);
    if (f.exists()) {
      f.delete();
    }
    f.createNewFile();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(f), "GBK"));
    bw.write("姓名 性别 年龄 业绩得分");
    for (Student student : students) {
      bw.write(System.lineSeparator());
      bw.write(student.toString());
    }
    bw.close();
  }

  private static List<Student> readStudents(String file) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(
        new FileInputStream(file), "GBK"));
    br.readLine();// 舍弃标题行
    String line = null;
    List<Student> students = new ArrayList<Student>();
    while ((line = br.readLine()) != null) {
      students.add(parseLine(line));
    }
    br.close();
    return students;
  }

  private static Student parseLine(String line) {
    String[] strs = line.split(" ");
    Student student = new Student();
    student.name = strs[0];
    student.gender = strs[1];
    student.age = Integer.parseInt(strs[2]);
    student.score = new BigDecimal(strs[3]);
    return student;
  }

  private static class Student implements Comparable<Student> {
    public String name;
    public String gender;
    public int age;
    public BigDecimal score;

    @Override
    public int compareTo(Student o) {
      return -score.compareTo(o.score);
    }

    public String toString() {
      return name + " " + gender + " " + age + " " + score.toPlainString();
    }
  }
}

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答