只要我們的class 實現了java.io.S " /> 色偷偷偷在线视频播放,美女黄网久久,一本色道久久综合狠狠躁的番外

色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

J2SE中的序列化的認識

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
  
  正確打印了結果。

jsp技術J2SE中的序列化的認識,轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 合山市| 新蔡县| 黑龙江省| 崇文区| 三原县| 英山县| 东兴市| 辽源市| 顺昌县| 忻城县| 井冈山市| 南充市| 轮台县| 南郑县| 慈利县| 大冶市| 扶风县| 江陵县| 芦山县| 华容县| 连南| 平阳县| 临夏市| 吉安县| 岳阳县| 兖州市| 隆林| 怀仁县| 安远县| 长阳| 教育| 安新县| 洛浦县| 哈巴河县| 榆林市| 四子王旗| 陈巴尔虎旗| 镇宁| 绩溪县| 望谟县| 右玉县|