学生管理系统(三刷)
添加IO流改进
序列化:
将对象变成字节序列(数组)
只有实现了序列化接口的类所产生的对象才能够被序列化
反序列化:
将序列恢复成对象
反序列化出来的对象他的序列编号与相对应的类不一致就会反序列化失败
- 需求:在学生信息管理系统(Map集合精进版)20190821的基础上进行改进,使系统内信息可以永久存储,即系统关闭后再次登录时,还可查询之前存储的内容。
- 步骤:使用IO流对信息进行读写。
- 在接口的实现类StudentServiceImpl中增加一个静态代码块,将Map集合中的信息存储到stu.txt文本文件中,使用ObjectInputStream对文件中的字节进行读取;
- 在接口中增加保存信息的方法exitSystem();方法在关闭系统时调用,使用ObjectOutputStream对map集合中的信息写入;
局部修改代码
- StudentServiceImpl
- 增加一个静态代码块。读取文件中的信息。
private static Map<String, Student> map = new HashMap<>();
static {
try {
File file = new File("src/stu.txt");
if(file.exists()) {
ObjectInputStream ois =
new ObjectInputStream(
new FileInputStream(file));
Map<String,Student> map1 = (Map<String, Student>) ois.readObject();
map.putAll(map1);
}
} catch (Exception e) {
System.out.println("文件读取失败");
}
}
- 接口exitSystem的实现方法。将Map集合写入文件以保存信息。
@Override
public void exitSystem() throws StudentException {
ObjectOutputStream oos =
new ObjectOutputStream(
new FileOutputStream("src/stu.txt"));
oos.writeObject(map);
oos.flush();
oos.close();
}
- 在Student类上添加Serializable标记
public class Student implements Serializable{
...
}
- Application
- 退出系统时调用方法。
case 9:
service.logout();
service.exitSystem();
System.out.println("系统成功关闭,欢迎下次使用!");
System.exit(-1);
break;
整体代码
- Student:
- 定义私有属性id、name、gender、score;
- Eclipse自动生成有参无参构造方法,getter和setter方法。
package com.briup.pojo;
public class Student {
private String id;//学号
private String name;//姓名
private String gender;//性别
private double score;//分数
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Student() {
}
public Student(String id, String name, String gender, double score) {
super();
this.id = id;
this.name = name;
this.gender = gender;
this.score = score;
}
}
- IStudentService:接口前面加“I”表示接口,定义各种功能的接口;
package com.briup.service;
import java.util.Collection;
import com.briup.exception.StudentException;
import com.briup.pojo.Student;
/**
* 接口
* @author Elvira
*
*/
public interface IStudentService {
/**
* 根据用户名密码去登录
* @param username 用户名
* @param password 密码
* @throws StudentException
*/
void login(String username, String password) throws