二级JAVA第六章辅导:对象串行化
先说序列化的好处:
(1)在网络中传输对象。
(2)在程序运行期间将对象保存在一个文件中,或者稍后在同一应用程序中写入然后读取该对象。
实现对象序列化有两个前提:
(1)要序列化的对象对应的类必须实现可序列化接口。
(2)要序列化的对象对应的类必须是公共的。
在Java中,有两个流类支持对象序列化:ObjectOutputStream和ObjectInputStream。
在对象序列化的过程中,如果类中有一些字段不想被序列化,就用transient来修饰。
下面是一个例子:
Customer.java
1导入Java . io . *;
2
3 public class Customer实现Serializable {
4 private String name,ID;
5临时私有字符串密码;
6私有浮动余额;
7
8公共客户(字符串名称、字符串ID、字符串密码、浮动余额){
9 this . name = name;
10这个。ID = ID
11 this . password = password;
12 this . balance = balance;
13 }
14
15公共字符串getName() {
16返回名称;
17 }
18
19公共字符串getID() {
20返回ID;
21 }
22
23公共字符串getPassword() {
24返回密码;
25 }
26
27 public float getBalance(){
28 return balance;29 }
30}
31
32
ObjectIODemo.java
1导入Java . io . *;
2
3 public class objectio demo {
4 public static void main(String[]args){
5 try {
6 object output stream object out = new object output stream
7(new BufferedOutputStream(new file output stream(" object . bin ")));
8
9客户cust =新客户("张三"," 0001 "," 1234 ",30000);
10 object out . writeobject(cust);
11 cust =新客户("李四"," 00002 "," 5678 ",10000);
12 object out . writeobject(cust);
13 object out . close();
14
15 ObjectInputStream objectIn = new ObjectInputStream
16(new BufferedInputStream(new file inputstream(" object . bin ")));
17
18 cust =(Customer)objectin . read object();
19显示(cust);
20
21 cust =(Customer)objectin . read object();
22显示(cust);
23
24 objectin . close();
25 }
26 catch(NotSerializableException e){
27 system . out . println(e . getmessage());
28 }
29 catch(ClassNotFoundException e){
30 system . out . println(e . getmessage());
31 }
32 catch(io exception e){
33 system . out . println(e . getmessage());
34 }
35 }
36
37私有静态void显示(客户cust){
38 system . out . println(" Name:"+cust . getname());
39 system . out . println(" ID:"+cust . getid());
40 system . out . println(" Password:"+cust . get Password());
41 system . out . println(" Balance:"+cust . get Balance());42 }
43}
44
0条评论