• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: 小 中 大 | 推荐给好友 上一篇 | 下一篇

J2SE中的序列化的认识

发布: 2007-7-01 18:47 | 作者: admin | 来源: | 查看: 11次 | 进入软件测试论坛讨论

领测软件测试网

  java中处处体现着简单的程序设计风格,序列化作为最常用的功能之一,在java中的设计尤为“简单”。在ObjectInputStream 和ObjectOutputStream的帮助下,我们可以轻松的实现序列化。

  只要我们的class 实现了java.io.Serializable接口,就可以利用ObjectOutputStream的writeObject()方法将一个对象序列化;利用ObjectInputStream的readObject()方法,可以返回读出的object对象。Serializable接口不需要我们实现任何方法。

  以下是一个例子,它能给我们一个感性的认识:

  Serial实现了就java.io.Serializable接口,是需要序列化的类。我们首先构造一个Serial的对象serial1然后将其保存(序列化)在一个文件中,而后再将其读出(反序列化),并打印其内容。

    package Stream;

    /**

    * @author favo yang

    */

    import java.io.*;

    public class Serial implements Serializable {

    int company_id;

    String company_addr;

    boolean company_flag;

    public Serial(){}//不同于c++,没有也可以

    public Serial(int company_id,String company_addr,boolean company_flag) {

    this.company_id=company_id;

    this.company_addr=company_addr;

    this.company_flag=company_flag;

    }

  public static void main(String[] args) {

    Serial serial1 = new Serial(752,"dayer street #5 building 02-287",false);//构造一个新的对象

    FileInputStream in=null;

    FileOutputStream out=null;

    ObjectInputStream oin=null;

    ObjectOutputStream oout=null;

  try {

     out = new FileOutputStream("5.txt");

     oout = new ObjectOutputStream(out);

     serial1.serialize(oout);//序列化

     oout.close();

     oout=null;

   in = new FileInputStream("5.txt");

     oin = new ObjectInputStream(in);

     Serial serial2 = Serial.deserialize(oin);//反序列化

     System.out.println(serial2);//打印结果

    } catch (Exception ex){

     ex.printStackTrace();

    } finally{

     try {

      if (in != null) {

       in.close();

      }

      if (oin != null) {

       oin.close();

      }

      if (out != null) {

       out.close();

      }

      if (oout != null) {

       oout.close();

      }

     } catch (IOException ex1) {

      ex1.printStackTrace();

     }

    }

    }

  /**

    * deserialize

    */

  public static Serial deserialize(ObjectInputStream oin) throws Exception{

    Serial s=(Serial)oin.readObject();

    return s;

    }

  public String toString() {

    return "DATA: "+company_id+" "+company_addr+" "+company_flag;

    }

  /**

    * serialize

    */

  public void serialize(ObjectOutputStream oout) throws Exception{

    oout.writeObject(this);

    }

    }

  运行结果:

  DATA: 752 dayer street #5 building 02-287 false

    

    正确打印了结果。

延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:[email protected] 电话:010-51297073

软件测试 | 领测国际 | ISTQB | ISTQB官网 | TMMi | TMMi认证 | 国际软件测试工程师认证 | 领测软件测试网