对象的序列化流,把对象以流的方式写入文件
构造方法
构造方法 | 作用 |
---|---|
ObjectOutStream(OutputStream out) | 创建使用指定OutputStream的 ObjectOutputStream对象 |
参数:
OutputStream out :字节输出流
特有的一个成员方法
方法 | 作用 |
---|---|
void writeObject(Object obj) | 将指定的对象写入到ObjectOutputStream |
使用步骤
package cn.zhuobo.day15.aboutObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Demo01ObjectOutputStream {
public static void main(String[] args) throws IOException {
Person p1 = new Person("猪八戒", 360);
writeObject(p1);
}
private static void writeObject(Person p) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day15-code/writeObject.txt"));
oos.writeObject(p);
oos.close();
}
}
但是要注意的是:要要序列化或者反序列化的对象应该是实现了一个java.io.Serializable接口的
Serializable接口:是一个标记类,实现该接口的类会获得一个标记,用来标记对象可以序列化或者反序列化。这个接口内部其实什么也没有,就仅仅是标记作用的标记类。没有实现该接口的类的对象要序列化就会抛出 NotSerializableException。
public class Person implements Serializable {
// body
}
对象的反序列化流,把文件保存的对象以流的方式读取出来
构造方法
构造方法 | 作用 |
---|---|
ObjectInputStream(InputStream in) | 创建一个从指定的 InputStream对象中读取的ObjectInputStream |
参数:
InputStream in : 字节输入流
特有的成员方法
方法 | 作用 |
---|---|
Object readObject() | 从ObjectInputStream中读取对象 |
使用步骤
package cn.zhuobo.day15.aboutObjectInputStream;
import cn.zhuobo.day15.aboutObjectOutputStream.Person;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Demo01ObjectInputStream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day15-code/writeObject.txt"));
Object o = ois.readObject();
ois.close();
// System.out.println(o.toString());
Person p = (Person)o;
System.out.println(p);
}
}
要注意的是
反序列化的前期:类必须实现了Serializable接口,其次是存在类对应的class文件
readObject方法已经声明了抛出ClassNotFoundException,因此这个异常也要处理,或者继续声明throws或者try catch
原文:https://www.cnblogs.com/zhuobo/p/10661232.html