人人做人人澡人人爽欧美,国产主播一区二区,久久久精品五月天,羞羞视频在线观看免费

當前位置:蘿卜系統(tǒng)下載站 > 技術(shù)開發(fā)教程 > 詳細頁面

談談J2SE中的序列化

談談J2SE中的序列化

更新時間:2022-08-16 文章作者:未知 信息來源:網(wǎng)絡 閱讀次數(shù):

java中處處體現(xiàn)著簡單的程序設計風格,序列化作為最常用的功能之一,在java中的設計尤為“簡單”。在ObjectInputStream 和ObjectOutputStream的幫助下,我們可以輕松的實現(xiàn)序列化。 

  只要我們的class 實現(xiàn)了java.io.Serializable接口,就可以利用ObjectOutputStream的writeObject()方法將一個對象序列化;利用ObjectInputStream的readObject()方法,可以返回讀出的object對象。Serializable接口不需要我們實現(xiàn)任何方法。 

  以下是一個例子,它能給我們一個感性的認識: 

  Serial實現(xiàn)了就java.io.Serializable接口,是需要序列化的類。我們首先構(gòu)造一個Serial的對象serial1然后將其保存(序列化)在一個文件中,而后再將其讀出(反序列化),并打印其內(nèi)容。 

  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);//構(gòu)造一個新的對象 
  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);//打印結(jié)果 
  } 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); 
 } 

  運行結(jié)果: 

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

  正確打印了結(jié)果。 

  現(xiàn)在序列化的功能還沒有被j2me支持,所以我們在j2me中是使用DataInputStream、DataoutputStream配合rms或者網(wǎng)絡實現(xiàn)序列化。

溫馨提示:喜歡本站的話,請收藏一下本站!

本類教程下載

系統(tǒng)下載排行

網(wǎng)站地圖xml | 網(wǎng)站地圖html
主站蜘蛛池模板: 丹寨县| 皋兰县| 涞源县| 丹阳市| 邢台市| 镇沅| 瑞安市| 微山县| 海口市| 安福县| 霍邱县| 顺平县| 石狮市| 嘉义县| 镇巴县| 霍林郭勒市| 固始县| 综艺| 云阳县| 永和县| 蓬安县| 北票市| 呈贡县| 吴忠市| 泰兴市| 抚松县| 咸丰县| 思茅市| 阳江市| 嵩明县| 内乡县| 蒲城县| 吐鲁番市| 嘉定区| 苏尼特左旗| 澜沧| 澎湖县| 蒲城县| 柳林县| 万盛区| 铜陵市|