对象的序列化流和对象反序列化流操作要求:
1,主要针对对象操作的流
2,解决的就是对象序列化与反序列化的问题
3,序列化就是将对象的数据写入到硬盘(将内存中的数据写入到持久化设备 序列化)
4,反序列化就是将硬盘中对象的数据读取的内存(将持久化设备中的数据读取到内存 反序列化)
示例:将people对象进行序列化和反序列化
public class ObjectStreamDemo {public static void main(String [] args) throws IOException, ClassNotFoundException {//write();read();}public static void read() throws IOException, ClassNotFoundException {FileInputStream fis =new FileInputStream("people.txt");ObjectInputStream ois =new ObjectInputStream(fis);People p =(People) ois.readObject();System.out.println(p.name);System.out.println(p.age);}
public static void write() throws IOException {People p =new People("张三",18);//将p进行序列化FileOutputStream fos =new FileOutputStream("people.txt");ObjectOutputStream os =new ObjectOutputStream(fos);//写出去的都是二进制信息os.writeObject(p);os.close();fos.close();
}
}
class People implements Serializable{String name;int age;public People(String name,int age){this.name= name;this.age =age;}
}
一个对象想要序列化需要实现Serializable接口
如果该对象当中某一个属性不想被序列化的话 加瞬态关键字 transient
静态变量没有被序列化
1.尽量别把所有属性都瞬态了 -> InvalidClassException
2.如果有多个同名称的类 在反序列化的时候也会出现->InvalidClassException 需要加 serialVersionUID
-> JVM