J2SE中的序列化的認識_JSP編程

來源:互聯網
上載者:User
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
  
  正確列印了結果。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.