大雀软件园

首页 软件下载 安卓市场 苹果市场 电脑游戏 安卓游戏 文章资讯 驱动下载
技术开发 网页设计 图形图象 数据库 网络媒体 网络安全 站长CLUB 操作系统 媒体动画 安卓相关
当前位置: 首页 -> 技术开发 -> 其他相关 -> 谈谈J2SE中的序列化

谈谈J2SE中的序列化

时间: 2021-07-31 作者:daque

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    精确打字与印刷结束果。    此刻序列化的功效还没有被j2me扶助,以是咱们在j2me中是运用datainputstream、dataoutputstream共同rms大概搜集实行序列化。

热门阅览

最新排行

Copyright © 2019-2021 大雀软件园(www.daque.cn) All Rights Reserved.