Java之序列化和反序列化

序列化的对象:

 1 package test_demo.SerializableOper;
 2 
 3 import java.io.Serializable;
 4 /*
 5 * 序列化对象需要实现序列号接口
 6 * */
 7 public class Book implements Serializable {
 8 //    指定序列化的jdk版本
 9 //    private static final long serialVersionUID =1L;
10     String name;
11     int price;
12 
13     public Book(String name, int price) {
14         this.name = name;
15         this.price = price;
16     }
17 
18     public String toString() {
19         return "name: " + name + ", price: " + price;
20     }
21 }

序列化和反序列化操作代码:

 1 package test_demo.SerializableOper;
 2 
 3 import java.io.*;
 4 
 5 /*
 6 * 序列化和反序列化举例
 7 * 序列化:把对象保存在硬盘的过程
 8 * 序列化的对象需要实现序列化接口
 9 * */
10 public class SerializableOper {
11     public static void main(String args[]) throws IOException, ClassNotFoundException {
12         Book book = new Book("阿甘正传", 55);
13         System.out.println(book);
14         String filePath = "C:\\testdata\\s\\book.txt";
15 
16         // 序列化
17         FileOutputStream fos = new FileOutputStream(filePath);
18         ObjectOutputStream oos = new ObjectOutputStream(fos);
19         oos.writeObject(book);
20         oos.close();
21         fos.close();
22 
23         // 反序列化
24         FileInputStream fis = new FileInputStream(filePath);
25         ObjectInputStream ois = new ObjectInputStream(fis);
26         Book b = (Book) ois.readObject();
27         System.out.println(b);
28 
29     }
30 }

book对象序列化后保存在C:\testdata\s\book.txt中。

 

posted @ 2017-12-07 10:10  星瑞  阅读(173)  评论(0编辑  收藏  举报