1 package FileDemo;
2
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.ObjectInputStream;
7 import java.io.ObjectOutputStream;
8 import java.io.Serializable;
9
10 class Person implements Serializable {
11 /*
12 * 接口标记,需要被序列化的对象必须实现Serializable接口 否则会出现NotSerializableException异常
13 */
14 // 自定义 serialVersionUID,用于判断类和对象是否为同一版本
15 private static final long serialVersionUID = 42L;
16 private String name;
17 /*
18 * 非静态数据不想被序列化可以使用transien修饰
19 */
20 private transient int age;//用transie修饰后name将不会被序列化
21
22 public Person(String name, int age) {
23 super();
24 this.name = name;
25 this.age = age;
26 }
27
28 public String getName() {
29 return name;
30 }
31
32 public void setName(String name) {
33 this.name = name;
34 }
35
36 public int getAge() {
37 return age;
38 }
39
40 public void setAge(int age) {
41 this.age = age;
42 }
43
44 }
45
46 public class ObjectStreamDemo {
47
48 /**
49 * @param args
50 * @throws Exception
51 */
52 public static void main(String[] args) throws Exception {
53
54 writeObject();
55 readObject();
56 }
57
58 private static void readObject() throws Exception {
59 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
60 "object.object"));
61 Person obj = (Person) ois.readObject();
62 System.out.println(obj.getName() + ":" + obj.getAge());
63 }
64
65 private static void writeObject() throws IOException, IOException {// 对象的序列化
66 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
67 "object.object"));
68 oos.writeObject(new Person("Java", 20));
69 oos.writeObject(new Person("python", 40));
70 oos.writeObject(new Person("linux", 50));
71 oos.writeObject(new Person("ruby", 46));
72 oos.close();
73 }
74
75 }