Java的序列化和反序列化

Java序列化和反序列化的简单实现,新建一个Java类实现Serializable接口,再定义一个标识来区别对象。

 1 import java.io.Serializable;
 2 
 3 public class Student implements Serializable {
 4 
 5     /**
 6      * serialVersionUID
 7      * 用来验证对象的唯一性
 8      */
 9     private static final long serialVersionUID = 1L;
10     
11     private String id;
12     private String name;
13     private char sex;
14     private int age;
15 
16     public String getId() {
17         return id;
18     }
19 
20     public void setId(String id) {
21         this.id = id;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31 
32     public char getSex() {
33         return sex;
34     }
35 
36     public void setSex(char sex) {
37         this.sex = sex;
38     }
39 
40     public int getAge() {
41         return age;
42     }
43 
44     public void setAge(int age) {
45         this.age = age;
46     }
47 
48     public Student(String id, String name, char sex, int age) {
49         this.id = id;
50         this.name = name;
51         this.sex = sex;
52         this.age = age;
53     }
54 
55     public Student() {
56     }
57 
58     @Override
59     public String toString() {
60         return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
61     }
62     

再通过ObjectOutputStream来把对象序列化,然后再通过ObjectInputStream来反序列化,多次写入记得flush下。

 1 Student st1 = new Student("1", "小明", '男', 15);
 2         Student st2 = new Student("2", "小华", '男', 20);
 3         try {
 4             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("student.txt"),true));
 5             oos.writeObject(st1);
 6             oos.flush();
 7             oos.writeObject(st2);
 8             oos.writeObject(null);//因为写入多个对象写一个null作为结束符方便循环读取。
 9             oos.close();
10         } catch (IOException e) {
11             e.printStackTrace();
12         }
13 
14         try {
15             Student st;
16             ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("student.txt")));
17             while ((st = (Student) ois.readObject()) != null) {
18                 System.out.println(st.toString());
19             }
20             ois.close();
21         } catch (IOException e) {
22             e.printStackTrace();
23         } catch (ClassNotFoundException e) {
24             e.printStackTrace();
25         }

 

posted @ 2019-06-11 21:16  零度放纵  阅读(145)  评论(0)    收藏  举报