SerializeDate() {
Date d = new Date ();
try {
FileOutputStream f =
new FileOutputStream ("date.ser"); //输出到date.ser这个文件中
ObjectOutputStream s =
new ObjectOutputStream (f);
s.writeObject (d); //写对象,将对象d写成是date.ser文件
s.close
(); //关闭流
} catch (IOException e) {
e.printStackTrace ();
} }
public static void main (String args[]) {
new SerializeDate();
}}
如图所示23-1,执行之后
图23-1
在DOS窗口中没有看到结果,但是在这个文件夹内发现了一个date.ser的文件。它就是对象d写入磁盘的状态。
如图23-2

图23-2
那么保存了之后怎么在把这个date.ser文件读出来呢?
实践:
import java.io.*;
import java.util.Date;
public class UnSerializeDate {
UnSerializeDate () {
Date d = null;
try { //使用FileInputStream类
FileInputStream f =
new FileInputStream ("date.ser");
ObjectInputStream s =
new ObjectInputStream (f);
d = (Date)
s.readObject ();//读对象
s.close
();
} catch (Exception e) {
e.printStackTrace (); }
System.out.println(
"从date.ser文件,读取Date对象 ");
System.out.println("日期是:
"+d);
}
public static void main (String args[]) {
new UnSerializeDate();
}}如图23-3所示读出时间

图23-3
上述源码打包下载
对于一个可以被序列化的类,它会实现一个Serializable的接口。那是个空接口,什么方法也没有只是一个标志而已。这在J2EE,(现在叫java
EE)中,使用EJB时是非常重要的。如果大家以后能继续学习学到EJB的时候,再具体了解。 |