国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

J2SE中的序列化的認識

2024-07-21 02:15:21
字體:
來源:轉載
供稿:網友

  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

    

    正確打印了結果。



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 密云县| 林西县| 报价| 菏泽市| 和硕县| 北京市| 奉贤区| 彰武县| 万盛区| 文化| 关岭| 镇原县| 阳江市| 淮滨县| 新密市| 新巴尔虎左旗| 曲阳县| 天全县| 西峡县| 衡水市| 徐闻县| 台南市| 信丰县| 黔东| 侯马市| 长泰县| 施秉县| 林芝县| 台北县| 八宿县| 金平| 都江堰市| 凤庆县| 奇台县| 富源县| 余江县| 历史| 仙居县| 普兰县| 晋中市| 兴宁市|