优化:1.将数据对象化的形式存入文件School.txt中
2.增加实现添加、删除、修改数据功能,并且数据会被永久保存下来
1.DataBase层的优化:
首先数据对象化就要应用ObjectInputStream读出文件中自定义类型的数据
注意:使用ObjectInputStream时,必须继承Serializable接口
public class DataBase implements Serializable{
//使用ObjectInputStream必须继承Serializable接口
List<School> sc = new ArrayList<>();
public List<School> getSchool(){
ObjectInputStream ois = null;
try { //处理异常
ois = new ObjectInputStream(new FileInputStream("D:\\install\\WONIU-J-Install\\Eclipse IDE\\Day13Sc\\School.txt"));
//应用ObjectInputStream的标准格式,让ois接入School.txt使其能够读取
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
return (List<School>) ois.readObject();
//返回读取到的School类型的list数据
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
return null;
}
2.Dao层的优化:
同理使用ObjectOutputStream时,必须继承Serializable接口
实现添加、删除、修改数据功能,并且数据会被永久保存下来主要是在这一层,操作也很简单,sc每次更改后都重写sc覆盖School.txt
public class DaoSchool implements Serializable{
DataBase data = new DataBase();
List<School> sc = data.getSchool();
/**
* 判断学校名称不重复
*/
public boolean NameReap(String name) {
return sc.stream().anyMatch(i->i.getName().equals(name));
}
/**
* 添加信息
*/
public void addsm(School s1) {
sc.add(s1);
WriteNewSc();
}
/**
* 重写新的sc
*/
public void WriteNewSc() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("School.txt"));
//使得oos接入School.txt,能够重写
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
oos.writeObject(sc); //重写School.txt
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 11、根据给定的学校名称删除信息
*/
public void delSchoolMassage(String a) {
sc = sc.stream().filter(i->!i.getName().equals(a))
.collect(Collectors.toList());
WriteNewSc();
}
/**
* 12、根据给定的旧的学校名称和新的学校名称修改学校名称
*/
public void fixSchoolMassage(String a, String b) {
sc.stream().filter(i->i.getName().equals(a))
.forEach(i->i.setName(b));
WriteNewSc();
}
}
3.View层和数据类型层
本次优化基本不影响这两层,只是注意添加新的方法以及继承Serializable接口