首页 >Java >java教程 >Java中序列化与ObjectOutputStream以及ObjectInputStream的详解

Java中序列化与ObjectOutputStream以及ObjectInputStream的详解

黄舟
黄舟原创
2017-09-22 11:13:071317浏览

这篇文章主要介绍了java序列化与ObjectOutputStream和ObjectInputStream的实例详解的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下

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; 
  } 
 
}

以上是Java中序列化与ObjectOutputStream以及ObjectInputStream的详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn