Java核心类库-IO-对象流(实现序列化与反序列化)

使用对象流来完成序列化和反序列化操作:

  ObjectOutputStream:通过writeObject()方法做序列化操作的

  ObjectInputStream:通过readObject方法来做反序列化操作的

做序列化操作必须存在对象的字节码对象。

 1 public class ObjectStreamDemo {
 2     public static void main(String[] args) throws Exception {
 3 
 4         File file = new File("obj.txt");
 5         //writeObject(file);
 6         readObject(file);
 7     }
 8 
 9     private static void readObject(File file) throws Exception {
10         ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
11         User user = (User) in.readObject();
12         System.out.println(user.getName());
13         in.close();
14     }
15 
16     private static void writeObject(File file) throws Exception {
17         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
18         out.writeObject(new User("wxd","123",21));
19         out.close();
20     }
21 }

 

posted @ 2017-05-23 22:17  wenxudong  阅读(142)  评论(0编辑  收藏  举报