将包含有学生学号、姓名、性别、专业、联系方式等信息的若干学生对象保存到文件stud.dat中,要求保密联系方式(即不保存),然后再读取文件中的学生信息并按学号的升序输出,用Java编程实现,并显示输出结果
时间: 2024-03-18 08:45:58 浏览: 39
用C语言写学生信息管理系统
好的,我会为您解答这个问题。
Java代码如下:
```java
import java.io.*;
import java.util.*;
class Student implements Serializable, Comparable<Student>{
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String gender;
private String major;
private transient String phone;
public Student(String id, String name, String gender, String major, String phone) {
this.id = id;
this.name = name;
this.gender = gender;
this.major = major;
this.phone = phone;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getMajor() {
return major;
}
public String getPhone() {
return phone;
}
@Override
public int compareTo(Student student) {
return this.id.compareTo(student.getId());
}
@Override
public String toString() {
return id + " " + name + " " + gender + " " + major;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("10001", "张三", "男", "计算机科学与技术", "13512345678"));
students.add(new Student("10002", "李四", "女", "软件工程", "13612345678"));
students.add(new Student("10003", "王五", "男", "信息安全", "13712345678"));
students.add(new Student("10004", "赵六", "女", "物联网工程", "13812345678"));
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("stud.dat"))) {
for(Student s : students) {
oos.writeObject(s);
}
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<Student> studentsFromFile = new ArrayList<>();
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("stud.dat"))) {
while(true) {
studentsFromFile.add((Student)ois.readObject());
}
} catch (EOFException e) {
// 文件读取结束
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
Collections.sort(studentsFromFile);
for(Student s : studentsFromFile) {
System.out.println(s.toString());
}
}
}
```
该程序定义了一个`Student`类,包含学号、姓名、性别、专业和联系方式等信息,其中联系方式被标记成`transient`,表示不会被序列化到文件中。程序先将4个`Student`对象保存到文件`stud.dat`中,然后再从该文件中读取学生信息,并按学号的升序输出。
阅读全文