序列化流:把对象按照流一样的方式存入文本文件 对象→流
ObjectOutputStream
方法:writeObject()
反序列化流:把文本文件的流对象还原成对象 流→对象
ObjectInputStream
!!! 要想对象实例化,必须先定义一个类 而且这个类必须加上接口:Serializable 这个接口交做标记接口
标记接口:不用添加方法
可能产生 ID不匹配的问题
解决方法:点击黄色警告线第二个即可, 表示变动的ID值
可以使用tainsient关键字使成员变量不被序列化
代码:
package cn.idcast3; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = -1623514706657398082L; private String name; private int age; 如果不想被序列化 private tainsient int age; public Person() { super(); // TODO Auto-generated constructor stub } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
package cn.idcast3; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ObjectStream { public static void main(String[] args) throws IOException, ClassNotFoundException { write(); read(); } private static void read() throws IOException, ClassNotFoundException { // TODO Auto-generated method stub ObjectInputStream ois = new ObjectInputStream(new FileInputStream( "oos.txt")); Object obj = ois.readObject(); ois.close(); System.out.println(obj); } private static void write() throws IOException, IOException { // TODO Auto-generated method stub ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( "oos.txt")); Person p = new Person("曾饺", 18); oos.writeObject(p); oos.close(); } }
时间: 2024-09-29 00:44:35