对象的序列化与反序列化的流。
⼀、构造⽅法
public ObjectOutputStream(OutputStream out);
public ObjectInputStream(InputStream in);
⼆、特有⽅法
void writeObject(Object obj);
Object readObject();
- 所有对象(包括 String 和数组)都可以通过 writeObject 写⼊。
- 可将多个对象或基元写⼊流中。
- 必须使⽤与写⼊对象时相同的类型和顺序从相应 ObjectInputstream 中读回对象。
三、条件
- 必须实现 java.io.Serializable 接⼝,否则会抛出 NotSerializableException。
序列化⼀个对象时,要求它的属性要么是基本数据类型,如果是引⽤数据类型,这个引⽤数据类型也必须实现Serializable接⼝。
- 该类的所有属性必须是可序列化的
如果有⼀个属性不需要可序列化的,则该属性必须注明是瞬态的,使⽤transient 关键字修饰。
- static修饰的不能被序列化
- 序列化⼀个数组,要求元素类型实现Serializable接⼝
四、⽰例
@Data
public class Test implements Serializable{
private String name;
private int age;
transient private String password;
private static boolean type;
public static void main(String[] args) {
Test test = new Test();
test.setName("wzy");
test.setAge(29);
test.setPassword("fdfdfd");
type=true;
String path = "/Users/wuzhengya/Desktop/test.txt";
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new
File(path))); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new
File(path)));
) {
oos.writeObject(test);
Test test2 = (Test) ois.readObject();
System.out.println(test2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}