概念:
对象的寿命随着生成该对象的程序的终止而终止。
对象的持续性:把对象的状态记录下来便于以后再生的能力。
对象串行化:将对象状态(实例变量)保存下来。
对象串行化的作用:
(1)把内存中对象状态(实例变量)保存到文件中;
(2)用套接字在网络上传送对象的时候;
(3)通过RMI传输对象时;
(4)将对象中需要持久保存的信息写入到数据库。
通过对象输出流的writeObject()和对象输入流的readObject()方法实现了对象的串行化(Serialized)和反串行化(Deserialized)
程序1:将系统对象写入文件import java.io.*;import java.util.*;public class writedate {public static void main(String args[]) {try {ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("storedate.dat"));out.writeObject(new Date());out.writeObject("hello world");System.out.println("写入完毕");} catch (IOException e) {}}}程序2:读取文件中的对象并显示出来import java.io.*;import java.util.*;public class readdate {public static void main(String args[]) {try{ObjectInputStream in=new ObjectInputStream(new FileInputStream("storedate.dat"));Date current=(Date)in.readObject();System.out.println("日期:"+current);String str=(String)in.readObject();System.out.println("字符串:"+str);} catch (IOException e) { }catch (ClassNotFoundException e) { }}}
