手机站
网通分站
电信主站
密 码:
用户名:
热门关键字:  虚拟主机  cn域名  域名注册  非法  seo
当前位置 : 主页>程序设计>Java技术>列表

谈谈J2SE中的序列化之一个感性的认识

来源:互联网 作者:west263.com 时间:2008-02-23 点击:
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

  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或者网络实现序列化。

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名
注册