码迷,mamicode.com
首页 > 其他好文 > 详细

序列化

时间:2016-05-23 20:52:48      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

如果一个类的对象需要序列化,就必须实现Serializable接口,比如下面的Person类,如果一个需要可序列化的类中有引用类型,则引用类型对应的类也必须是可序列化的

 1 import java.io.Serializable;
 2 
 3 
 4 public class Person implements Serializable {
 5 
 6     //类的版本号,用来区分序列化的对象是哪个版本,
 7     // 也就是说可以用来对比硬盘上的对象和程序中的类是否版本相同
 8     private static final long serialVersionUID = 1L;
 9     private String name;
10     private int age;
11 
12 
13     public Person(int age, String name) {
14         this.age = age;
15         this.name = name;
16     }
17 
18     public void setAge(int age) {
19         this.age = age;
20     }
21 
22     public void setName(String name) {
23         this.name = name;
24     }
25 
26     public String getName() {
27         return name;
28     }
29 
30     public int getAge() {
31         return age;
32     }
33 
34     @Override
35     public String toString() {
36         return "Person{" +
37                 "name=‘" + name + ‘\‘‘ +
38                 ", age=" + age +
39                 ‘}‘;
40     }
41 }

将对象序列化写入文件,然后从文件中读出对象

 1 @Test
 2     public void testSerializable() throws Exception {
 3         Person person = new Person(12,"Bond");
 4 
 5         OutputStream out = new FileOutputStream("obj.txt");
 6     
 7     //对象输出流也是一个包装流
 8         ObjectOutputStream  objectOutputStream = new ObjectOutputStream(out);
 9 
10         objectOutputStream.writeObject(person);
11 
12         out.close();
13         objectOutputStream.close();
14 
15 
16     }
17 
18     @Test
19     public void testObjectInputStream()throws Exception{
20         
21     InputStream in = new FileInputStream("obj.txt");
22         ObjectInputStream objectInputStream = new ObjectInputStream(in);
23 
24         Object obj = objectInputStream.readObject();
25         System.out.println(obj);
26 
27         objectInputStream.close();
28         in.close();
29 
30     }

 

序列化

标签:

原文地址:http://www.cnblogs.com/hotpoint/p/5521102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!