Java中的IO流(ObjectInputStream)

ObjectInputStream:

ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化。
只有支持 java.io.Serializable 或 java.io.Externalizable 接口的对象才能从流读取。
注意:如果一个类被序列化之后,改动了这个类的属性或者方法之类,反序列化的时候,会报错(序列化版本异常)
如何解决?
使该类的序列版本号与从流中读取的类描述符的版本号匹配(保持一致)
在类中添加如下代码
private static final long serialVersionUID = 10000L;
该类的序列版本号与从流中读取的类描述符的版本号不匹配
local class serialVersionUID = 1407881350363140898 该类的序列版本号
stream classdesc serialVersionUID = 2768250842175706371 流中读取的类描述符的版本号
注意:如果某些属性不想序列化,可以在属性的前面加关键字transient
private transient String name;
加了transient关键字的属性,不会被序列化进去,会按照属性默认值来处理

注意:如果一个类中,有另外一个类,当做这个类的属性,如果要序列化这个类,那么这个属性也得实现序列化接口

public static void main(String[] args) throws  IOException,
                                              ClassNotFoundException {
		//1:创建反序列化流  (把文件中的对象读取到程序中)
		ObjectInputStream ois = new ObjectInputStream(
				new FileInputStream("student.txt"));
		//2:读取对象  一次读取一个对象
		/*Object obj = null;
		while((obj = ois.readObject())!=null){
			Student stu = (Student)obj;
			System.out.println(stu.getName()+stu.getAge()+stu.getSex());
		}*/
		//3:直接读取集合对象
		ArrayList<Student> al = (ArrayList<Student>)ois.readObject();
		for (Student stu : al) {
			System.out.println(stu.getName()+stu.getAge()+stu.getSex());
		}
		//4:关闭流
		ois.close();
	
	}

猜你喜欢

转载自blog.csdn.net/qq_44013790/article/details/85342345