序列化
序列化:Object => String
反序列化:String => Object
核心原理
序列化是把对象转成字符串的过程,那么转换之后的字符串,就保存在文件中,所以Java的序列化是基于文件IO的。
Serializable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
| public class Main {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
boolean goOn = true;
while (goOn) {
System.out.println("1写入,2读取,0退出");
int answer = scanner.nextInt();
switch (answer) {
case 1:
writeObject();
break;
case 2:
readObject();
break;
default:
goOn = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写入
* @throws IOException
*/
private static void writeObject() throws IOException {
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("test.txt"));
Student student = new Student();
stream.writeObject(student);
}
/**
* 读取
* @throws IOException
* @throws ClassNotFoundException
*/
private static void readObject() throws IOException, ClassNotFoundException {
ObjectInputStream stream = new ObjectInputStream(new FileInputStream("test.txt"));
Student student = (Student) stream.readObject();
System.out.println("读到对象:" + student.toString());
}
/**
* 测试序列化类
*/
private static class Student implements Serializable {
/**
* 注意:
* 1.必须是static final long serialVersionUID;
* 2.在反序列化时,Java根据这个来判定类型是否发生了变化,如果变化会抛出InvalidClassException(类型无效异常);
* 3.并不是必须,Java会默认生成;
* 4.如果两个端同时同时操作序列化文件,A端的serialVersionUID变了,比如增加了字段,然后进行了序列化;而B端的serialVersionUID没有变,是可以成功反序列化的,但是会忽略A端新增的字段。
*/
private static final long serialVersionUID = 2L;
public String name = "张三";
public int age = 18;
private final Teacher teacher = new Teacher();
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", teacher=" + teacher +
'}';
}
}
/**
* 序列化类型中的引用类型必须也是可序列化的
*/
private static class Teacher implements Serializable {
public String name = "李四";
public int age = 22;
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
|
Externalizable
提供了两个抽象方法:
- writeExternal(ObjectOutPut out)
- readExternal(ObjectOutPut out)
Parcelable