Java序列化与反序列化


  只有实现了Serializable或Externalizable接口的类的对象才能被序列化,否则抛出异常。

假定一个Student类,它的对象需要序列化,可以有如下三种方法:

方法一:若Student类仅仅实现了Serializable接口,则可以按照以下方式进行序列化和反序列化

ObjectOutputStream采用默认的序列化方式,对Student对象的非transient的实例变量进行序列化。

ObjcetInputStream采用默认的反序列化方式,对对Student对象的非transient的实例变量进行反序列化。

方法二:若Student类仅仅实现了Serializable接口,并且还定义了readObject(ObjectInputStream in)和writeObject(ObjectOutputSteam out),则采用以下方式进行序列化与反序列化。

ObjectOutputStream调用Student对象的writeObject(ObjectOutputStream out)的方法进行序列化。

ObjectInputStream会调用Student对象的readObject(ObjectInputStream in)的方法进行反序列化。

方法三:若Student类实现了Externalnalizable接口,且Student类必须实现readExternal(ObjectInput in)和writeExternal(ObjectOutput out)方法,则按照以下方式进行序列化与反序列化。

ObjectOutputStream调用Student对象的writeExternal(ObjectOutput out))的方法进行序列化。

ObjectInputStream会调用Student对象的readExternal(ObjectInput in)的方法进行反序列化。


  1. public class UseStudent  
  2. {  
  3.  public static void main(String[] args)  
  4.  {  
  5.   Student st = new Student("Tom",'M',20,3.6);  
  6.   File file = new File("O:\\Java\\com\\jieke\\io\\student.txt");  
  7.   try  
  8.   {  
  9.    file.createNewFile();  
  10.   }  
  11.   catch(IOException e)  
  12.   {  
  13.    e.printStackTrace();  
  14.   }  
  15.   try  
  16.   {  
  17.    //Student对象序列化过程  
  18.    FileOutputStream fos = new FileOutputStream(file);  
  19.    ObjectOutputStream oos = new ObjectOutputStream(fos);  
  20.    oos.writeObject(st);  
  21.    oos.flush();  
  22.    oos.close();  
  23.    fos.close();  
  24.   
  25.    //Student对象反序列化过程  
  26.    FileInputStream fis = new FileInputStream(file);  
  27.    ObjectInputStream ois = new ObjectInputStream(fis);  
  28.    Student st1 = (Student) ois.readObject();  
  29.    System.out.println("name = " + st1.getName());  
  30.    System.out.println("sex = " + st1.getSex());  
  31.    System.out.println("year = " + st1.getYear());  
  32.    System.out.println("gpa = " + st1.getGpa());  
  33.    ois.close();  
  34.    fis.close();  
  35.   }  
  36.   catch(ClassNotFoundException e)  
  37.   {  
  38.    e.printStackTrace();  
  39.   }  
  40.   catch (IOException e)  
  41.   {  
  42.    e.printStackTrace();  
  43.   }               
  44.  }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值