设计一个学生student类,包含学号、姓名、出生日期、性别等字段 从input.txt(从附件下载)中读取其中的学生信息,并存入学生集合list中 对学生集合list进行排序,按照出生日期从早到晚排序(即年龄由大到小) 将排序后的学生集合list输出到output.txt文件中,输出格式同input.txt:一行一个学生,依次输出学号、姓名、出生日期、性别并用空格隔开用java语音
时间: 2024-02-03 12:02:40 浏览: 28
以下是Java代码实现:
```java
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
class Student implements Comparable<Student> {
private String id;
private String name;
private Date birthDate;
private String gender;
public Student(String id, String name, Date birthDate, String gender) {
this.id = id;
this.name = name;
this.birthDate = birthDate;
this.gender = gender;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public Date getBirthDate() {
return birthDate;
}
public String getGender() {
return gender;
}
@Override
public int compareTo(Student o) {
return this.birthDate.compareTo(o.birthDate);
}
@Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthDateString = sdf.format(birthDate);
return id + " " + name + " " + birthDateString + " " + gender;
}
}
public class Main {
public static void main(String[] args) throws IOException, ParseException {
List<Student> studentList = new ArrayList<>();
// 读取文件
File inputFile = new File("input.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\\s+");
String id = fields[0];
String name = fields[1];
Date birthDate = new SimpleDateFormat("yyyy-MM-dd").parse(fields[2]);
String gender = fields[3];
studentList.add(new Student(id, name, birthDate, gender));
}
reader.close();
// 排序
Collections.sort(studentList);
// 写入文件
File outputFile = new File("output.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Student student : studentList) {
writer.write(student.toString());
writer.newLine();
}
writer.close();
}
}
```
其中,`Student`类实现了`Comparable`接口,重写了`compareTo`方法,以便使用`Collections.sort`函数进行排序。在`toString`方法中,使用`SimpleDateFormat`类将`Date`类型的出生日期转换为字符串格式,方便输出。读取和写入文件的操作使用了Java的IO流。