11.1-Java IO流-对10.2进行优化-文件中存取对象化的数据-23/05/05

优化: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接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值