tbwshc

序列化在IO中读写对象的使用

    序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。序列化是为了解决在对对象流进行读写操作时所引发的问题。

  序列化的实现:将需要被序列化的类实现Serializable接口,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。
 写对象和读对象的时候一定要使用序列化:

  import java.io.*;

  class Product implements Serializable {

  private static final long serialVersionUID = 1L;

  private float price;

  private float tax;

  public Product(float price) {

  this.price = price;

  tax = (float)(price*0.20);

  }

  public String toString() {

  return "price:"+price+",tax:"+tax;

  }

  }

  public class CmdDemo {

  public static void main(String[] strtb) throws Exception {

  Product p1 = new Product(100);

  ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream

  ("d:\product.txt"));

  os.writeObject(p1);

  os.close();

  ObjectInputStream is = new ObjectInputStream(new FileInputStream

  ("d:\product.txt"));

  Product p2 = (Product) is.readObject();

  System.out.println(p2.toString());

  }

  }

posted on 2013-09-17 15:12 chen11-1 阅读(251) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: