当前位置: 移动技术网 > IT编程>开发语言>Java > Java IO流对象的序列化和反序列化实例详解

Java IO流对象的序列化和反序列化实例详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

java—io流 对象的序列化和反序列化

序列化的基本操作

  1.对象序列化,就是将object转换成byte序列,反之叫对象的反序列化。

  2.序列化流(objectoutputstream),writeobject 方法用于将对象写入输出流中;

  反序列化流(objectinputstream),readobject 方法用于从输入流中读取对象。

  3.序列化接口(serializeable)

  对象必须实现序列化接口,才能进行序列化,否则会出现异常。这个接口没有任何方法,只是一个标准。

package com.test.io;

import java.io.fileinputstream;
import java.io.fileoutputstream;import java.io.objectinputstream;
import java.io.objectoutputstream;

public class objectserialzetest {
  /**
   * 对象的序列化
   * @param file
   * @throws exception
   */
  public void objectoutput (string file) throws exception {
    objectoutputstream oos = new objectoutputstream(new fileoutputstream(file));
    student stu = new student("002", "张四", 12);
    oos.writeobject(stu);
    oos.flush();
    oos.close();
  }
  /**
   * 对象的反序列化
   * @param file
   * @throws exception
   */
  public void objectinput(string file) throws exception {
    objectinputstream ois = new objectinputstream(new fileinputstream(file));
    student stu = (student)ois.readobject();
    system.out.println(stu.tostring());
    ois.close();
  }

  public static void main(string[] args) throws exception {
    string file = "f:\\javaio\\obj.dat";
    objectserialzetest ost = new objectserialzetest();
    ost.objectoutput(file);
    ost.objectinput(file);
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网