當兩個程序在進行遠端通信時,彼此可以發送各種類型的資料。無論是何種類型的資料,都會以二進制序列的形式在網絡上傳送。發送方需要把這個java對象轉換為位元組序列,才能在網絡上傳送;接收方則需要把位元組序列再恢複為java對象。
把java對象轉換為位元組序列的過程稱為對象的序列化。
把位元組序列恢複為java對象的過程稱為對象的反序列化。
對象的序列化主要有兩種用途:
1)
把對象的位元組序列永久地儲存到硬碟上,通常存放在一個檔案中;
2)
在網絡上傳送對象的位元組序列。
java.io.objectoutputstream代表對象輸出流,它的writeobject(object
obj)方法可對參數指定的obj對象進行序列化,把得到的位元組序列寫到一個目标輸出流中。
java.io.objectinputstream代表對象輸入流,它的readobject()方法從一個源輸入流中讀取位元組序列,再把它們反序列化為一個對象,并将其傳回。、
隻有實作了serializable和externalizable接口的類的對象才能被序列化。externalizable接口繼承自serializable接口,實作externalizable接口的類完全由自身來控制序列化的行為,而僅實作serializable接口的類可以采用預設的序列化方式
。
對象序列化包括如下步驟:
建立一個對象輸出流,它可以包裝一個其他類型的目标輸出流,如檔案輸出流;
通過對象輸出流的writeobject()方法寫對象。
對象反序列化的步驟如下:
建立一個對象輸入流,它可以包裝一個其他類型的源輸入流,如檔案輸入流;
通過對象輸入流的readobject()方法讀取對象。
for example:

import java.io.*;
public class
objectdemo
{
public
static void main(string[] args)
{
try
{
objectoutputstream
objectout=new objectoutputstream(new bufferedoutputstream(new
fileoutputstream("object.bin")));
customer
cus=new customer("wang","0001","pddd",3000);
objectout.writeobject(cus);
objectout.close();
objectinputstream
objectin=new objectinputstream(new bufferedinputstream(new
fileinputstream("object.bin")));
cus=(customer)objectin.readobject();
system.out.println("name:"+cus.getname());
system.out.println("id:"+cus.getid());
system.out.println("password:"+cus.getpassword());
system.out.println("salary:"+cus.getsalary());
}
catch
(notserializableexception e)
system.out.println(e.getmessage());
catch(classnotfoundexception
e)
system.out.println(e.getmessage());
catch(ioexception
}
}
class customer implements
serializable
private
string name,id;
transient private string
password;
private float salary;
public customer(string
name,string id,string password,float salary)
this.name=name;
this.id=id;
this.password=password;
this.salary=salary;
public string
getname()
return
name;
getid()
id;
getpassword()
public float
getsalary()
salary;
};