Java.io.ObjectOutputStream.writeObject() 方法
描述
java.io.ObjectOutputStream.writeObject(Object obj) 方法将指定的对象写入 ObjectOutputStream。 写入对象的类、类的签名、类的非瞬态和非静态字段的值及其所有超类型。 可以使用 writeObject 和 readObject 方法覆盖类的默认序列化。 此对象引用的对象是可传递写入的,因此可以通过 ObjectInputStream 重建对象的完整等效图。
声明
以下是 java.io.ObjectOutputStream.writeObject() 方法的声明。
public final void writeObject(Object obj)
参数
obj − 要写入的对象。
返回值
此方法不返回值。
异常
InvalidClassException − 序列化使用的类有问题。
NotSerializableException − 某些要序列化的对象没有实现 java.io.Serializable 接口。
IOException − 底层 OutputStream 引发的任何异常。
示例
下面的例子展示了 java.io.ObjectOutputStream.writeObject() 方法的使用。
package com.tutorialspoint;
import java.io.*;
public class ObjectOutputStreamDemo {
public static void main(String[] args) {
String s = "Hello world!";
int i = 897648764;
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(i);
// close the stream
oout.close();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
// read and print what we wrote before
System.out.println("" + (String) ois.readObject());
System.out.println("" + ois.readObject());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Hello world! 897648764

