java序列化與反序列化

 開始學習java序列化與反序列化,寫出了個初步代碼。

這是一個用戶類:

  1. import java.io.Serializable; 
  2.  
  3. public class User implements Serializable { 
  4.     /** 
  5.      *  
  6.      */ 
  7.     private static final long serialVersionUID = 1L; 
  8.     public String name; 
  9.     public String sex; 
  10.     public int age; 
  11.  
  12.     public User() { 
  13.     } 
  14.  
  15.     public User(String name, String sex, int age) { 
  16.         this.name = name; 
  17.         this.sex = sex; 
  18.         this.age = age; 
  19.     } 
  20.      
  21.     public String toString(){ 
  22.         return "用戶名:"+name+"性別:"+sex+"年齡:"+age; 
  23.     } 
  24.  

下面將對其進行序列化與反序列化操作:

  1. import java.io.FileInputStream; 
  2. import java.io.FileOutputStream; 
  3. import java.io.ObjectInputStream; 
  4. import java.io.ObjectOutputStream; 
  5. import java.util.Date; 
  6.  
  7. public class Test { 
  8.     public static void serialize(String filePath) { 
  9.         try { 
  10.             ObjectOutputStream out = new ObjectOutputStream( 
  11.                     new FileOutputStream(filePath)); 
  12.             out.writeObject("序列化時間爲:"); 
  13.             out.writeObject(new Date()); 
  14.             User user = new User("admin""male"10); 
  15.             out.writeObject(user); 
  16.             out.close(); 
  17.         } catch (Exception e) { 
  18.             System.out.println(e.toString()); 
  19.         } 
  20.     } 
  21.     public static void deserialize(String filePath){ 
  22.         try { 
  23.             ObjectInputStream in=new ObjectInputStream(new FileInputStream(filePath)); 
  24.             String time=(String)(in.readObject()); 
  25.             Date date=(Date)(in.readObject()); 
  26.             User user=(User)(in.readObject()); 
  27.             System.out.println(time); 
  28.             System.out.println(date); 
  29.             System.out.println(user); 
  30.         } catch (Exception e) { 
  31.             System.out.println(e.toString()); 
  32.         } 
  33.     } 
  34.     public static  void main(String[]args){ 
  35.         serialize("E:\\testserialize.txt"); 
  36.         System.out.println("serialize completed!"); 
  37.         deserialize("E:\\testserialize.txt"); 
  38.         System.out.println("deserialize completed!"); 
  39.     } 
  40.      

運行之後,在控制檯輸出:

 

  1. serialize completed! 
  2. 序列化時間爲: 
  3. Wed Jun 13 23:31:54 CST 2012 
  4. 用戶名:admin性別:male年齡:10 
  5. deserialize completed! 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章