序列化、反序列化

package com.phone.shuyinghengxie;

import java.io.Serializable;


/*
                 一个类的对象要想序列化成功,必须知足两个条件:
                该类必须实现 java.io.Serializable 对象。
                该类的全部属性必须是可序列化的。若是有一个属性不是可序列化的,
                    则该属性必须注明是短暂的。
                若是你想知道一个Java标准类是不是可序列化的,请查看该类的文档。
                检验一个类的实例是否能序列化十分简单, 只须要查看该类有没有
                实现java.io.Serializable接口。
 */

public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}
/*
序列化对象
    ObjectOutputStream 类用来序列化一个对象,以下的SerializeDemo例子实例化了一个Employee对象,并将该对象序列化到一个文件中。
    该程序执行后,就建立了一个名为employee.ser文件。该程序没有任何输出,可是你能够经过代码研读来理解程序的做用。
    注意: 当序列化一个对象到文件时, 按照Java的标准约定是给文件一个.ser扩展名。
*/

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}                
/*
反序列化对象
    下面的DeserializeDemo程序实例了反序列化,/tmp/employee.ser存储了Employee对象。
*/
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}