高级流
ObjectOutputStream:序列化流(对象输出流)
public final void writeObject(Object obj) - 禁止重写
ObjectInputStream:反序列化流(对象输入流)
public final Object readObject()
序列化
package Test21_Demo.Demo04;/*
@create 2020--12--14--10:33
*/
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializableDemo {
public static void main(String[] args) throws IOException {
//准备被序列化的对象
Person person = new Person("Jack.Ma", 18);
//进行序列化操作
FileOutputStream fos = new FileOutputStream("person.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//开始序列化
oos.writeObject(person);
//关闭流
oos.close();
}
}
反序列化
package Test21_Demo.Demo04;/*
@create 2020--12--14--10:33
*/
import java.io.*;
public class SerializableDemo2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//进行反序列化操作
FileInputStream fis = new FileInputStream("person.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
//开始反序列化
Person person = (Person) ois.readObject();
System.out.println(person.getName() + " " + person.getAge());
System.out.println(person);
//关闭流
ois.close();
}
}