例子
以下示例显示java.io.ObjectInputStream.close()方法的用法。
package com.jc2182;
import java.io.*;
public class DefaultReadObject {
public static void main(String[] args) throws Exception {
// Instantiates ObjectOutputStream , ObjectInputStream
// FileInputStream and FileOutputStream
FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);
// By using writeObject() method is to
// write object to Serialized class
obj_out_stm.writeObject(new DefaultObjectClass());
obj_out_stm.flush();
// By using readObject() method is to
// read an object from the Serialized class
DefaultObjectClass def_obj = (DefaultObjectClass) obj_in_stm.readObject();
// Using both readObject and defaultReadObject();
System.out.println("obj_in_stm.defaultReadObject(): " + def_obj.str);
System.out.println("obj_in_stm.defaultReadObject(): " + def_obj.in);
}
static class DefaultObjectClass implements Serializable {
String str = "Java Programming";
Integer in = new Integer(10);
private void readObject(ObjectInputStream obj_stm) throws IOException, ClassNotFoundException {
// By using defaultReadObject() method is
// to read non-static fields of the present
// class from the ObjectInputStream
obj_stm.defaultReadObject();
}
}
}
让我们编译并运行以上程序,这将产生以下结果-
obj_in_stm.defaultReadObject(): Java Programming
obj_in_stm.defaultReadObject(): 10