-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectInputOutputStreamTest.java
More file actions
63 lines (55 loc) · 1.79 KB
/
Copy pathObjectInputOutputStreamTest.java
File metadata and controls
63 lines (55 loc) · 1.79 KB
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
package tutorial.java;
import org.junit.Test;
import java.io.*;
public class ObjectInputOutputStreamTest {
@Test
public void test(){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("test.data"));
/*Serialization 序列化对象, 使其具备持久性 */
oos.writeObject("Hello world, 我是中国人");
oos.flush();
oos.writeObject(new Person("Bob", 23));
oos.flush();
oos.writeObject(new Person("Bob", 23, 1001, new Account(1999.23)));
oos.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void test2(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("test.data"));
/* 对象的反序列化, 还原对象到内存中 */
// write String first, then read it first
Object object = ois.readObject();
String str = (String) object;
Person p1 = (Person) ois.readObject();
System.out.println(str);
System.out.println(p1);
Person p2 = (Person) ois.readObject();
System.out.println(p2);
}catch (IOException | ClassNotFoundException e){
e.printStackTrace();
}finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}