import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* 序列化:把对象按照流一样的方式写到文本文件或者在网络中传输。
*
* ObjectOutputStream:把对象写到文件。 序列化。
* ObjectInputStream:从文件中读取对象。反序列化。
* 看到序列化的内容后,我们要掌握的内容:
* A:看到一个类实现了序列化接口,就要知道,该类的对象可以被序列化,
* 也就是说可以写到文本文件,或者在网络中传输。
* B:看到一个类实现了序列化接口,我们可以点击鼠标解决黄色警告问题,
* 并且,这样解决后,还能保证做一些简单的修改,不影响我以前的数据。
*/
public class ObjectStreamDemo {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
// write();//序列化
read();// 反序列化
}
// 从文件中读取对象。反序列化
public static void read() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"oos.txt"));
Object obj = ois.readObject();
ois.close();
System.out.println(obj);
}
// 把对象写到文件。 序列化
public static void write() throws IOException {
// 创建对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"oos.txt"));
// 创建Person对象
Person p = new Person("欧巴马", 49);
// 调用方法
// public final void writeObject(Object obj)
oos.writeObject(p);
// 释放资源
oos.close();
}
}