圖文淺析Java序列化和反序列化
序列化
序列化:將對(duì)象轉(zhuǎn)換為二進(jìn)制序列在網(wǎng)絡(luò)中傳輸或保存到磁盤
反序列化:從網(wǎng)絡(luò)或磁盤中將二進(jìn)制序列轉(zhuǎn)換為對(duì)象
注意:
對(duì)象必須實(shí)現(xiàn)Serializable接口
對(duì)象的所有屬性都要能序列化(Integer,Byte等都進(jìn)行了序列化)
String
Integer
案例:
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.大象測試類
public class ElephantTest { public static final String PATH = "D:\\elephant"; static void write(Elephant elephant){ //創(chuàng)建對(duì)象輸出流 try( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) { //寫入對(duì)象 out.writeObject(elephant); } catch (IOException e) { e.printStackTrace(); } } static Object read(){ //創(chuàng)建對(duì)象輸出流 try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) { //寫入對(duì)象 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); } }
運(yùn)行結(jié)果:
寫入D盤的對(duì)象:
總結(jié)
到此這篇關(guān)于Java序列化和反序列化的文章就介紹到這了,更多相關(guān)Java序列化和反序列化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中的FailureAnalyzer使用詳解
這篇文章主要介紹了SpringBoot中的FailureAnalyzer使用詳解,Spring Boot的FailureAnalyzer是一個(gè)接口,它用于在Spring Boot應(yīng)用啟動(dòng)失敗時(shí)提供有關(guān)錯(cuò)誤的詳細(xì)信息,這對(duì)于開發(fā)者來說非常有用,因?yàn)樗梢詭椭覀兛焖僮R(shí)別問題并找到解決方案,需要的朋友可以參考下2023-12-12JSR303校驗(yàn)前端傳遞的數(shù)據(jù)方式
這篇文章主要介紹了JSR303校驗(yàn)前端傳遞的數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01詳解Java對(duì)象序列化為什么要使用SerialversionUID
這篇文章主要介紹了詳解Java對(duì)象序列化為什么要使用SerialversionUID,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11java刪除文件時(shí)總是返回false,刪不掉的解決方案
這篇文章主要介紹了java刪除文件時(shí)總是返回false,刪不掉的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09java開發(fā)validate方法中校驗(yàn)工具類詳解
這篇文章主要為大家介紹了java開發(fā)validate方法中校驗(yàn)工具類詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09