欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java序列化与ObjectOutputStream和ObjectInputStream的实例详解

程序员文章站 2024-03-02 13:18:16
java序列化与objectoutputstream和objectinputstream的实例详解 一个测试的实体类: public class param...

java序列化与objectoutputstream和objectinputstream的实例详解

一个测试的实体类:

public class param implements serializable { 
 
  private static final long serialversionuid = 5187074869820982336l; 
   
   
  private integer param1; 
  private string param2; 
 
  public integer getparam1() { 
    return param1; 
  } 
 
  public void setparam1(integer param1) { 
    this.param1 = param1; 
  } 
 
  public string getparam2() { 
    return param2; 
  } 
 
  public void setparam2(string param2) { 
    this.param2 = param2; 
  } 
 
} 

 测试:

public class main { 
 
  public static void main(string[] args) throws exception { 
    serializeparam(); 
     
    param param = deserializeparam(); 
    system.out.println(messageformat.format("param1={0},param2={1}", param.getparam1(), param.getparam2())); 
  } 
 
  /** 
   * 将实体类序列化到本地 
   * @throws filenotfoundexception 
   * @throws ioexception 
   */ 
  private static void serializeparam() throws filenotfoundexception, ioexception { 
    param param = new param(); 
    param.setparam1(123); 
    param.setparam2("asdf"); 
     
    objectoutputstream oo = new objectoutputstream(new fileoutputstream( new file("e:/param.txt") )); 
    oo.writeobject(param); 
    system.out.println("person对象序列化成功!"); 
    oo.close(); 
  } 
   
  /** 
   * 反序列化 
   * @return 
   * @throws exception 
   * @throws ioexception 
   */ 
  private static param deserializeparam() throws exception, ioexception { 
    objectinputstream ois = new objectinputstream(new fileinputstream( new file("e:/param.txt"))); 
    param param = (param) ois.readobject(); 
    system.out.println("person对象反序列化成功!"); 
    ois.close(); 
    return param; 
  } 
 
} 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望通过本文能帮助到大家,谢谢大家对本站的支持!