java对象的序列化和反序列化

 

/*
java中对象的序列化和反序列化    序列化将对象信息保存至文件等永久设备   反序列化从设备读取对象信息
在内从中根据信息重=构对象但是并不调用构造函数 序列化只保存对象的非静态成员  静态成员和方法不保存
transient 修饰的成员可以被忽略 不背保存  
在进行序列化和反序列化的时候必须实现   Serializable 接口   
在进行串行化的时候 会自动调用  对象的
 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;
 这两个方法可以在对象中进行重写来灵活运用  是唯一可以再外部调用的私有方法


*/
import java.io.* ;
class  Test
{
 public static void main(String []args)  throws Exception
 { 
   Student s1=new Student(1,"w22");
   Student s2=new Student(2,"w3322");
   Student s3=new Student(4,"w24432");
   FileOutputStream fos=new FileOutputStream("ob.txt");
   ObjectOutputStream oos=new ObjectOutputStream(fos);
   oos.writeObject(s1) ;   //将对象写入文件输出流
   oos.writeObject(s2) ;
   oos.writeObject(s3) ;
   oos.close() ;//关闭
  
  
  
   FileInputStream fis=new FileInputStream("ob.txt");  //打开文件输入流
   ObjectInputStream bis=new ObjectInputStream(fis);  //连接输入流 
   Student tem=null;
   for(int n=0;n<3;n++)
   { 
      tem=(Student)bis.readObject()  ;
      System.out.println(tem.num+"  "+tem.name) ;  //输出从文件加载的对象的信息
   }
   bis.close();//关闭对象输入流
  
  
 }
 
}
class Student  implements   Serializable   //实现 Serializable  接口实现串行化 
{  
   int num ;
   String name ;
    Student(int num,String name)
    {
      this.num=num;
      this.name=name;
    }
     private void writeObject(java.io.ObjectOutputStream oos)   throws IOException  //序列化 会调用的函数 我们可以重写这个函数好似唯一可以被外部调用的静态函数
     {
       oos.writeInt(num) ;
       oos.writeUTF(name);
       System.out.println("Object of Class  Student is serializing!") ;//提示信息
        
      }
 
    private void readObject(java.io.ObjectInputStream ois)   throws IOException, ClassNotFoundException
    {
      this.num=ois.readInt() ;
      this.name=ois.readUTF() ;
      System.out.println("Object of Class  Student is deserializing !") ;  //输出提示信息
     
    }
 
 
}

posted on 2011-08-16 21:14  风尘女子  阅读(109)  评论(0编辑  收藏  举报

导航