Java.io.ObjectInputStream.readObject() 方法
描述
java.io.ObjectInputStream.readObject() 方法从 ObjectInputStream 中读取一个对象。 读取对象的类、类的签名以及类及其所有超类型的非瞬态和非静态字段的值。 可以使用 writeObject 和 readObject 方法覆盖类的默认反序列化。 此对象引用的对象被传递读取,以便通过 readObject 重建对象的完整等效图。
当根对象的所有字段和它引用的对象完全恢复时,根对象将完全恢复。 此时,对象验证回调将根据其注册的优先级按顺序执行。 回调由对象注册(在 readObject 特殊方法中),因为它们是单独恢复的。
对于 InputStream 的问题和不应反序列化的类会引发异常。 所有异常对 InputStream 来说都是致命的,并使其处于不确定状态; 由调用者忽略或恢复流状态。
声明
以下是 java.io.ObjectInputStream.readObject() 方法的声明。
public final Object readObject()
参数
NA
返回值
该方法返回从流中读取的对象。
异常
ClassNotFoundException − 找不到序列化对象的类。
InvalidClassException − 序列化使用的类有问题。
StreamCorruptedException − 流中的控制信息不一致。
OptionalDataException − 在流中找到原始数据而不是对象。
IOException − 任何常见的输入/输出相关异常。
示例
下面的例子展示了 java.io.ObjectInputStream.readObject() 方法的使用。
package com.tutorialspoint;
import java.io.*;
public class ObjectInputStreamDemo {
public static void main(String[] args) {
String s = "Hello World";
byte[] b = {'e', 'x', 'a', 'm', 'p', 'l', 'e'};
try {
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(s);
oout.writeObject(b);
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
// read and print an object and cast it as string
System.out.println("" + (String) ois.readObject());
// read and print an object and cast it as string
byte[] read = (byte[]) ois.readObject();
String s2 = new String(read);
System.out.println("" + s2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Hello World example

