您好,歡迎來(lái)電子發(fā)燒友網(wǎng)! ,新用戶?[免費(fèi)注冊(cè)]

您的位置:電子發(fā)燒友網(wǎng)>源碼下載>java源碼下載>

java序列化的幾種方式

大?。?/span>0.4 MB 人氣: 2017-09-27 需要積分:1

  一.Java序列化的作用

  有的時(shí)候我們想要把一個(gè)Java對(duì)象變成字節(jié)流的形式傳出去,有的時(shí)候我們想要從一個(gè)字節(jié)流中恢復(fù)一個(gè)Java對(duì)象。例如,有的時(shí)候我們想要

  把一個(gè)Java對(duì)象寫入到硬盤或者傳輸?shù)骄W(wǎng)路上面的其它計(jì)算機(jī),這時(shí)我們就需要自己去通過(guò)java把相應(yīng)的對(duì)象寫成轉(zhuǎn)換成字節(jié)流。對(duì)于這種通用

  的操作,我們?yōu)槭裁床皇褂媒y(tǒng)一的格式呢?沒(méi)錯(cuò),這里就出現(xiàn)了java的序列化的概念。在Java的OutputStream類下面的子類ObjectOutput-

  Stream類就有對(duì)應(yīng)的WriteObject(Object object) 其中要求對(duì)應(yīng)的object實(shí)現(xiàn)了java的序列化的接口。

  為了更好的理解java序列化的應(yīng)用,我舉兩個(gè)自己在開(kāi)發(fā)項(xiàng)目中遇到的例子:

  1)在使用tomcat開(kāi)發(fā)JavaEE相關(guān)項(xiàng)目的時(shí)候,我們關(guān)閉tomcat后,相應(yīng)的session中的對(duì)象就存儲(chǔ)在了硬盤上,如果我們想要在tomcat重啟的

  時(shí)候能夠從tomcat上面讀取對(duì)應(yīng)session中的內(nèi)容,那么保存在session中的內(nèi)容就必須實(shí)現(xiàn)相關(guān)的序列化操作。

  2)如果我們使用的java對(duì)象要在分布式中使用或者在rmi遠(yuǎn)程調(diào)用的網(wǎng)絡(luò)中使用的話,那么相關(guān)的對(duì)象必須實(shí)現(xiàn)java序列化接口。

  親愛(ài)的小伙伴,大概你已經(jīng)了解了java序列化相關(guān)的作用,接下來(lái)們來(lái)看看如何實(shí)現(xiàn)java的序列化吧。~

  二。實(shí)現(xiàn)java對(duì)象的序列化和反序列化。

  Java對(duì)象的序列化有兩種方式。

  a.是相應(yīng)的對(duì)象實(shí)現(xiàn)了序列化接口Serializable,這個(gè)使用的比較多,對(duì)于序列化接口Serializable接口是一個(gè)空的接口,它的主要作用就是

  標(biāo)識(shí)這個(gè)對(duì)象時(shí)可序列化的,jre對(duì)象在傳輸對(duì)象的時(shí)候會(huì)進(jìn)行相關(guān)的封裝。這里就不做過(guò)多的介紹了。

  下面是一個(gè)實(shí)現(xiàn)序列化接口的Java序列化的例子:非常簡(jiǎn)單

  packagecom.shop.domain; importjava.util.Date;publicclassArticleimplementsjava.io.Serializable{privatestaticfinallongserialVersionUID =1L; privateInteger id; privateString title; //文章標(biāo)題privateString content; // 文章內(nèi)容privateString faceIcon; //表情圖標(biāo)privateDate postTime; //文章發(fā)表的時(shí)間privateString ipAddr; //用戶的ipprivateUser author; //回復(fù)的用戶publicInteger getId() { returnid; }publicvoidsetId(Integer id) { this.id = id; } publicString getTitle() { returntitle; }publicvoidsetTitle(String title) { this.title = title; } publicString getContent() { returncontent; }publicvoidsetContent(String content) { this.content = content; } publicString getFaceIcon() {returnfaceIcon; } publicvoidsetFaceIcon(String faceIcon) { this.faceIcon = faceIcon; }publicDate getPostTime() { returnpostTime; } publicvoidsetPostTime(Date postTime) {this.postTime = postTime; } publicUser getAuthor() { returnauthor; }publicvoidsetAuthor(User author) { this.author = author; } publicString getIpAddr() {returnipAddr; } publicvoidsetIpAddr(String ipAddr) { this.ipAddr = ipAddr; } }

  b.實(shí)現(xiàn)序列化的第二種方式為實(shí)現(xiàn)接口Externalizable,Externlizable的部分源代碼如下:

  * @seejava.io.ObjectInput * @seejava.io.Serializable * @sinceJDK1 .1*/publicinterfaceExternalizableextendsjava.io.Serializable{/** * The object implements the writeExternal method to save its contents * by calling the methods of DataOutput for its primitive values or

  沒(méi)錯(cuò),Externlizable接口繼承了java的序列化接口,并增加了兩個(gè)方法:

  - void writeExternal(ObjectOutput out) throws IOException; - void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

  首先,我們?cè)谛蛄谢瘜?duì)象的時(shí)候,由于這個(gè)類實(shí)現(xiàn)了Externalizable 接口,在writeExternal()方法里定義了哪些屬性可以序列化,

  哪些不可以序列化,所以,對(duì)象在經(jīng)過(guò)這里就把規(guī)定能被序列化的序列化保存文件,不能序列化的不處理,然后在反序列的時(shí)候自動(dòng)調(diào)

  用readExternal()方法,根據(jù)序列順序挨個(gè)讀取進(jìn)行反序列,并自動(dòng)封裝成對(duì)象返回,然后在測(cè)試類接收,就完成了反序列。

  所以說(shuō)Exterinable的是Serializable的一個(gè)擴(kuò)展。

  為了更好的理解相關(guān)內(nèi)容,請(qǐng)看下面的例子:

  packagecom.xiaohao.test; importjava.io.Externalizable; importjava.io.FileInputStream;importjava.io.FileNotFoundException; importjava.io.FileOutputStream;importjava.io.IOException; importjava.io.ObjectInput; importjava.io.ObjectInputStream;importjava.io.ObjectOutput; importjava.io.ObjectOutputStream;importjava.text.SimpleDateFormat; importjava.util.Date; /** * 測(cè)試實(shí)體類 *@author小浩 * @創(chuàng)建日期 2015-3-12 */class Person implements Externalizable{privatestaticfinallongserialVersionUID = 1L;《br》 String userName; String password; String age; publicPerson(String userName, String password, String age) { super();this.userName = userName; this.password = password; this.age = age; } publicPerson() {super(); } publicString getAge() { returnage; } publicvoidsetAge(String age) { this.age = age; } publicString getUserName() { returnuserName; } publicvoidsetUserName(String userName) { this.userName = userName; } publicString getPassword() { returnpassword; }publicvoidsetPassword(String password) { this.password = password; } /** * 序列化操作的擴(kuò)展類 */@OverridepublicvoidwriteExternal(ObjectOutput out) throwsIOException { //增加一個(gè)新的對(duì)象Date date= newDate(); out.writeObject(userName); out.writeObject(password); out.writeObject(date); } /** * 反序列化的擴(kuò)展類 */@OverridepublicvoidreadExternal(ObjectInput in) throwsIOException, ClassNotFoundException { //注意這里的接受順序是有限制的哦,否則的話會(huì)出錯(cuò)的// 例如上面先write的是A對(duì)象的話,那么下面先接受的也一定是A對(duì)象。。.userName=(String) in.readObject(); password=(String) in.readObject(); SimpleDateFormat sdf=newSimpleDateFormat( “yyyy-MM-dd”); Date date=(Date)in.readObject(); System.out.println( “反序列化后的日期為:”+sdf.format(date)); } @OverridepublicStringtoString() { //注意這里的年齡是不會(huì)被序列化的,所以在反序列化的時(shí)候是讀取不到數(shù)據(jù)的return“用戶名:”+userName+ “密 碼:”+password+ “年齡:”+age; } } /** * 序列化和反序列化的相關(guān)操作類 *@author小浩 * @創(chuàng)建日期 2015-3-12 Java學(xué)習(xí)交流QQ群:589809992 我們一起學(xué)Java! */class Operate{ /** * 序列化方法 *@throwsIOException *@throwsFileNotFoundException */publicvoidserializable(Person person)throwsFileNotFoundException, IOException{ ObjectOutputStream outputStream=newObjectOutputStream( newFileOutputStream( “a.txt”)); outputStream.writeObject(person); } /** * 反序列化的方法 *@throwsIOException *@throwsFileNotFoundException *@throwsClassNotFoundException */publicPersondeSerializable() throwsFileNotFoundException, IOException, ClassNotFoundException{ ObjectInputStream ois= newObjectInputStream( newFileInputStream( “a.txt”));return(Person) ois.readObject(); } } /** * 測(cè)試實(shí)體主類 *@author小浩 * @創(chuàng)建日期 2015-3-12 */publicclassTest{publicstaticvoidmain(String[] args) throwsFileNotFoundException, IOException, ClassNotFoundException { Operate operate= newOperate(); Person person= newPerson( “小浩”, “123456”, “20”); System.out.println( “為序列化之前的相關(guān)數(shù)據(jù)如下:\n”+person.toString()); operate.serializable(person); Person newPerson=operate.deSerializable(); System.out.println( “-------------------------------------------------------”); System.out.println( “序列化之后的相關(guān)數(shù)據(jù)如下:\n”+newPerson.toString()); } }

  首先,我們?cè)谛蛄谢疷serInfo對(duì)象的時(shí)候,由于這個(gè)類實(shí)現(xiàn)了Externalizable 接口,在writeExternal()方法里定義了哪些屬性可

  以序列化,哪些不可以序列化,所以,對(duì)象在經(jīng)過(guò)這里就把規(guī)定能被序列化的序列化保存文件,不能序列化的不處理,然后在反序列

  的時(shí)候自動(dòng)調(diào)用readExternal()方法,根據(jù)序列順序挨個(gè)讀取進(jìn)行反序列,并自動(dòng)封裝成對(duì)象返回,然后在測(cè)試類接收,就完成了反

  序列。

非常好我支持^.^

(0) 0%

不好我反對(duì)

(0) 0%

      發(fā)表評(píng)論

      用戶評(píng)論
      評(píng)價(jià):好評(píng)中評(píng)差評(píng)

      發(fā)表評(píng)論,獲取積分! 請(qǐng)遵守相關(guān)規(guī)定!

      ?