下面程序段是创建一个Date类的对象并把它串行化保存到文件中,该对象表示的是运行时刻的日期及时间,请将程序补充完整。
import java.util.*;
impor java.io.*;
public class SerializeDate
Date d;
SerializeDate()
d=new Date();
try
FileOutputStream f=new FileOutputStream( “date.ser");
ObjectOutputStream s=new ObjectOutputStream(f);
【12】
f.close();
catch(IOException e)
e.printStackTrace();
public static void main(String args[])
SerializeDate b=new SerializeDate();
System.out.println(”The saved date is:"+b.d.toString());
参考答案:s.writeObiect(d);
解析: 本题考查把一个对象写到一个流中。这个操作比较简单,是通过调用 ObjectOutputStream类的writeObject()方法实现的。ObjectOutputStream类是一种过滤流类,因此,对象流必须在其他流的基础上进行构造。题目程序中SerializeDate类的构造方法SerializeDate()中,对象流s是在一个文件输出流上构造的,通过s将一个 Date类的对象串行化到一个名为date.ser中,具体是通过调用ObiectOutputStream类的方法writeObject()将该对象写到对象输出流s中,而对象最终是保存在外存date.ser文件中的。