深入理解Java序列化與反序列化
一、前言
序列化:將對象轉(zhuǎn)換為二進制序列在網(wǎng)絡(luò)中傳輸或保存到磁盤
反序列化:從網(wǎng)絡(luò)或磁盤中將二進制序列轉(zhuǎn)換為對象
注意:
- 對象必須實現(xiàn)Serializable接口
- 對象的所有屬性都要能序列化(Integer,Byte等都進行了序列化)
1.1 String
1.2 Integer
二、案例
2.1 編寫大象類
public class Elephant implements Serializable { private String name; private String age; private String sex; public Elephant(String name, String age, String sex) { this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Elephant{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", sex='" + sex + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
2.2 大象測試類
public class ElephantTest { public static final String PATH = "D:\\elephant"; static void write(Elephant elephant){ //創(chuàng)建對象輸出流 try( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) { //寫入對象 out.writeObject(elephant); } catch (IOException e) { e.printStackTrace(); } } static Object read(){ //創(chuàng)建對象輸出流 try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) { //寫入對象 return in.readObject(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { Elephant elephant7 = new Elephant("小紅象", "18", "男"); write(elephant7); Elephant elephant1 = (Elephant) read(); System.out.println(elephant1); System.out.println(elephant7); System.out.println(elephant1==elephant7); } }
三、運行結(jié)果
寫入D盤的對象:
到此這篇關(guān)于深入理解Java序列化與反序列化的文章就介紹到這了,更多相關(guān)Java序列化與反序列化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
帶你了解Java數(shù)據(jù)結(jié)構(gòu)和算法之無權(quán)無向圖
這篇文章主要為大家介紹了Java數(shù)據(jù)結(jié)構(gòu)和算法之無權(quán)無向圖?,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01解決spring-boot-maven-plugin報紅的問題
這篇文章主要給大家介紹一下如何解決spring-boot-maven-plugin報紅的問題,文中通過圖文講解的非常詳細,具有一定的參考價值,需要的朋友可以參考下2023-08-08springboot中用fastjson處理返回值為null的屬性值
在本篇文章里小編給大家整理的是一篇關(guān)于springboot中用fastjson處理返回值問題詳解內(nèi)容,需要的朋友們參考下。2020-03-03Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐
本文主要介紹了Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08