Java中可以通過對象流將一個(gè)序列化的對象保存到硬盤中,或者硬盤中讀取一個(gè)對象。對象流的存儲(chǔ)和讀取包含以下幾點(diǎn)內(nèi)容:
1、所保存的對象必須實(shí)現(xiàn)Serializable接口。
2、 所保存的對象的屬性也必須實(shí)現(xiàn)Serializable接口。
3、 最好要給該對象提供一個(gè)版本號(hào),private static final long serialVersionId。
下面是一個(gè)對象流存儲(chǔ)和讀取一個(gè)對象的流程圖:
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
|
class Person implements Serializable { //實(shí)現(xiàn)序列化接口,其中的String,int也都是實(shí)現(xiàn)了Serializable的,不然就會(huì)報(bào)錯(cuò) private static final long serialVersionUID = 7072662597320618920L; String name; int age; public Person(String name, int age) { this .name = name; this .age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]" ; } } public class ObjectStreamTest { private ObjectInputStream ips; @Test public void outStreamTest() throws Exception { File file = new File( "D:/person.txt" ); Person p1 = new Person( "hanking" , 24 ); Person p2 = new Person( "Hust" , 120 ); FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream ops = new ObjectOutputStream(fos); ops.writeObject(p2); ops.writeObject(p1); ops.flush(); ops.close(); } @Test public void InStreamTest() throws Exception { ips = new ObjectInputStream( new FileInputStream( "D:/person.txt" )); Person p1 = (Person) ips.readObject(); System.out.println( ":" + p1); Person p2 = (Person) ips.readObject(); System.out.println( ":" + p2); ips.close(); } } |
以上這篇Java中的對象流總結(jié)(必看篇)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。