服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > JDK > 查看文档

谈谈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
  
  正确打印了结果。

扫描关注微信公众号