java学生管理系统输入输出流实现读写,图形化界面
时间: 2023-11-01 10:28:50 浏览: 44
为了实现Java学生管理系统的输入输出流读写,可以使用Java标准库中的FileInputStream/FileOutputStream和ObjectInputStream/ObjectOutputStream类。
当需要保存学生信息时,可以将学生对象序列化为字节流后写入到文件中,代码示例:
```java
try {
FileOutputStream fos = new FileOutputStream("students.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(student); // student为学生对象
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
```
当需要读取学生信息时,可以从文件中读取字节流并反序列化为学生对象,代码示例:
```java
try {
FileInputStream fis = new FileInputStream("students.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Student student = (Student) ois.readObject(); // Student为学生类
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
```
为了实现图形化界面,可以使用Java Swing或JavaFX等GUI库。在界面上添加按钮或菜单项,通过事件监听器来响应用户操作,更新学生信息并进行读写操作。例如,当用户点击保存按钮时,程序将当前学生对象序列化并写入到文件中;当用户点击读取按钮时,程序从文件中读取学生对象并在界面上展示。
代码示例:
```java
// 创建保存按钮
JButton saveButton = new JButton("保存");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
FileOutputStream fos = new FileOutputStream("students.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(student); // student为当前学生对象
oos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
// 创建读取按钮
JButton loadButton = new JButton("读取");
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
FileInputStream fis = new FileInputStream("students.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Student student = (Student) ois.readObject(); // Student为学生类
ois.close();
// 在界面上展示学生信息
showStudentInfo(student);
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
}
});
```