java中编写一个程序,实现一下功能,要求 设计一个学生student类,包含学号、姓名、出生日期、性别等字段 从input.txt(从附件下载)中读取其中的学生信息,并存入学生集合list中 对学生集合list进行排序,按照出生日期从早到晚排序(即年龄由大到小) 将排序后的学生集合list输出到output.txt文件中,输出格式同input.txt:一行一个学生,依次输出学号、姓名、出生日期、性别并用空格隔开
时间: 2024-02-05 20:10:51 浏览: 29
以下是实现该功能的Java程序:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class StudentSorter {
public static void main(String[] args) {
// 从 input.txt 中读取学生信息
List<Student> students = readStudentsFromFile("input.txt");
// 对学生集合进行排序
Collections.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getBirthDate().compareTo(s2.getBirthDate());
}
});
// 将排序后的学生集合输出到 output.txt 文件中
writeStudentsToFile(students, "output.txt");
System.out.println("学生信息已排序并输出到 output.txt 文件中。");
}
private static List<Student> readStudentsFromFile(String filePath) {
List<Student> students = new ArrayList<>();
File file = new File(filePath);
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fields = line.split("\\s+");
String id = fields[0];
String name = fields[1];
LocalDate birthDate = LocalDate.parse(fields[2], DateTimeFormatter.ofPattern("yyyy-MM-dd"));
char gender = fields[3].charAt(0);
Student student = new Student(id, name, birthDate, gender);
students.add(student);
}
} catch (IOException e) {
System.out.println("读取文件出错:" + e.getMessage());
}
return students;
}
private static void writeStudentsToFile(List<Student> students, String filePath) {
File file = new File(filePath);
try (FileWriter writer = new FileWriter(file)) {
for (Student student : students) {
String line = student.getId() + " " + student.getName() + " "
+ student.getBirthDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " "
+ student.getGender();
writer.write(line + "\n");
}
} catch (IOException e) {
System.out.println("写入文件出错:" + e.getMessage());
}
}
}
class Student {
private String id;
private String name;
private LocalDate birthDate;
private char gender;
public Student(String id, String name, LocalDate birthDate, char gender) {
this.id = id;
this.name = name;
this.birthDate = birthDate;
this.gender = gender;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public LocalDate getBirthDate() {
return birthDate;
}
public char getGender() {
return gender;
}
}
```
程序的主要步骤如下:
1. 定义一个 `Student` 类表示学生,包含学号、姓名、出生日期、性别等字段。
2. 从 `input.txt` 文件中读取学生信息,并将每个学生信息封装成一个 `Student` 对象存入一个 `List<Student>` 集合中。
3. 使用 `Collections.sort()` 方法对学生集合进行排序,按照出生日期从早到晚排序。
4. 将排序后的学生集合输出到 `output.txt` 文件中,输出格式与 `input.txt` 文件相同。
5. 定义一个 `readStudentsFromFile()` 方法读取文件中的学生信息,返回一个 `List<Student>` 集合。
6. 定义一个 `writeStudentsToFile()` 方法将学生集合写入文件,写入格式与 `input.txt` 文件相同。