注意点:
1.必须要有 private static final long serialVersionUID=5343541254343464L;这个属性 值可以不一样
2.每个属性都必须是可序列化的 就是说 必须继承Serializable这个接口
package java1;
import org.junit.Test;
import java.io.*;
/**
* @Author Lin
* @CreateTime 2021/4/20 15:08
*/
public class StreamTest {
@Test
public void test3() throws Exception{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("Person.bat"));
//类的存储
oos.writeObject(new Person("张三", 12223));
oos.close();
//类的读取
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("Person.bat"));
System.out.println(ois.readObject());
ois.close();
}
}
class Person implements Serializable {
//这个serialVersionUID必须要有 如果没有在重新读取的时候
//如果类发生过变化 会导致出错
private static final long serialVersionUID=5343541254343464L;
//这个类的每个属性都必须是可序列化的 就是说 必须继承Serializable这个接口
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "姓名:"+name+" 年龄:"+ age;
}
}