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 String name;
15 int age;
16
17 public Person(String name, int age) {
18 super();
19 this.name = name;
20 this.age = age;
21 }
22
23 public String getName() {
24 return name;
25 }
26
27 public void setName(String name) {
28 this.name = name;
29 }
30
31 public int getAge() {
32 return age;
33 }
34
35 public void setAge(int age) {
36 this.age = age;
37 }
38
39 }
40
41 public class ObjectStreamDemo {
42
43 /**
44 * @param args
45 * @throws Exception
46 */
47 public static void main(String[] args) throws Exception {
48
49 writeObject();
50 readObject();
51 }
52
53 private static void readObject() throws Exception {
54 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
55 "object.object"));
56 Person obj = (Person)ois.readObject();
57 System.out.println(obj.getName()+":"+obj.getAge());
58 }
59
60 private static void writeObject() throws IOException, IOException {// 对象的序列化
61 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
62 "object.object"));
63 oos.writeObject(new Person("Java", 20));
64 oos.writeObject(new Person("python", 40));
65 oos.writeObject(new Person("linux", 50));
66 oos.writeObject(new Person("ruby", 46));
67 oos.close();
68 }
69
70 }