`

对象的序列化与反序列化

阅读更多
import java.io.*;
import java.util.Date;

  /**
  * 对象的序列化和反序列化测试类.    
  */

  public class ObjectServer {

        /**

        * @param args

        */

        public static void main(String[] args) throws Exception {

              ObjectOutputStream out = new ObjectOutputStream

                      (new FileOutputStream("objectFile.dat"));

              //序列化对象

              Customer customer = new Customer("周瑜", 24);

              out.writeObject("你好!");

              out.writeObject(new Date());

              out.writeObject(customer);

              out.writeInt(123); //写入基本类型数据

              out.close();

              //反序列化对象

              ObjectInputStream in = new ObjectInputStream

                      (new FileInputStream("objectFile.dat"));

              System.out.println("obj1=" + (String) in.readObject());

              System.out.println("obj2=" + (Date) in.readObject());

              Customer obj3 = (Customer) in.readObject();

              System.out.println("obj3=" + obj3);

              int obj4 = in.readInt();

              System.out.println("obj4=" + obj4);

              in.close();

        }

}

  class Customer implements Serializable {

        private String name;

        private int age;

        public Customer(String name, int age) {

              this.name = name;

              this.age = age;

        }

        public String toString() {

              return "name=" + name + ", age=" + age;

        }

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics