java readobject_Object readObject()

Object readObject()

描述 (Description)

java.io.ObjectInputStream.readObject()方法从ObjectInputStream中读取一个对象。 读取对象的类,类的签名,以及类的非瞬态和非静态字段及其所有超类型的值。 可以使用writeObject和readObject方法覆盖类的默认反序列化。 这个对象引用的对象是可传递的,因此readObject可以重建完整的等效对象图。

当根对象的所有字段及其引用的对象完全恢复时,它将完全恢复。 此时,对象验证回调基于其注册的优先级按顺序执行。 回调由对象(在readObject特殊方法中)注册,因为它们是单独还原的。

对于InputStream和不应反序列化的类的问题,会抛出异常。 所有异常对InputStream都是致命的,并使其处于不确定状态; 由调用者忽略或恢复流状态。

声明 (Declaration)

以下是java.io.ObjectInputStream.readObject()方法的声明。public final Object readObject()

参数 (Parameters)

NA

返回值 (Return Value)

此方法返回从流中读取的对象。

异常 (Exception)ClassNotFoundException - 找不到序列化对象的类。

InvalidClassException - 序列化使用的类有问题。

StreamCorruptedException - 流中的控制信息不一致。

OptionalDataException - 在流中找到原始数据而不是对象。

IOException - 任何常见的输入/输出相关异常。

例子 (Example)

以下示例显示了java.io.ObjectInputStream.readObject()方法的用法。package com.iowiki;

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值