1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.FileNotFoundException;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.ObjectInputStream;
8 import java.io.ObjectOutputStream;
9 import java.io.OutputStream;
10 import java.io.Serializable;
11 import java.util.Arrays;
12
13 class Student implements Serializable
14 {
15 /**
16 * 序列化的类
17 */
18 private static final long serialVersionUID = 1L;
19 public String name;
20 public int age;
21 public String IdCard;
22 public Student(String name, int age, String idCard) {
23 super();
24 this.name = name;
25 this.age = age;
26 IdCard = idCard;
27 }
28 public String getName() {
29 return name;
30 }
31 public void setName(String name) {
32 this.name = name;
33 }
34 public int getAge() {
35 return age;
36 }
37 public void setAge(int age) {
38 this.age = age;
39 }
40 public String getIdCard() {
41 return IdCard;
42 }
43 public void setIdCard(String idCard) {
44 IdCard = idCard;
45 }
46 @Override
47 public String toString() {
48 return "Student [name=" + name + ", age=" + age + ", IdCard=" + IdCard + "]";
49 }
50 public Student() {}
51 }
52
53
54 public class OneTime {
//写对象
55 private static void writeObject()
56 { //序列化的类,实例化对象数组
57 Student[] st = {new Student("wei",19,"1803050208"),
58 new Student("zhong",20,"1803050209"),
59 new Student("wang",21,"1803050211"),
60 new Student("li",18,"1803050210")};
61 File f = new File("C:\\Users\\Easyboyxxx\\st.obj");
//对象流
62 try {
63 OutputStream out = new FileOutputStream(f);
64 ObjectOutputStream ob = new ObjectOutputStream(out);
65 ob.writeObject(st);
66 ob.close();
67 } catch (FileNotFoundException e) {
68 e.printStackTrace();
69 } catch (IOException e) {
70 e.printStackTrace();
71 }
72 }
73 private static void readObject()
74 {
75 File f = new File("C:\\Users\\Easyboyxxx\\st.obj");
76 try {
77 InputStream in = new FileInputStream(f);
78 ObjectInputStream ob = new ObjectInputStream(in);
79 Student[] st = (Student[])ob.readObject(); //注意读出的是对象数组,不是单个对象
80 ob.close();
81 System.out.println(Arrays.toString(st));
82 } catch (FileNotFoundException e) {
83 e.printStackTrace();
84 } catch (IOException e) {
85 e.printStackTrace();
86 } catch (ClassNotFoundException e) {
87 e.printStackTrace();
88 }
89
90 }
//主方法调用读写方法。
91 public static void main(String args[])
92 {
93 writeObject();
94 readObject();
95
96 }
97
98 }