圖文淺析Java序列化和反序列化
序列化
序列化:將對象轉(zhuǎn)換為二進制序列在網(wǎng)絡(luò)中傳輸或保存到磁盤
反序列化:從網(wǎng)絡(luò)或磁盤中將二進制序列轉(zhuǎn)換為對象
注意:
對象必須實現(xiàn)Serializable接口
對象的所有屬性都要能序列化(Integer,Byte等都進行了序列化)
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)建對象輸出流 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盤的對象:
總結(jié)
到此這篇關(guān)于Java序列化和反序列化的文章就介紹到這了,更多相關(guān)Java序列化和反序列化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中的FailureAnalyzer使用詳解
這篇文章主要介紹了SpringBoot中的FailureAnalyzer使用詳解,Spring Boot的FailureAnalyzer是一個接口,它用于在Spring Boot應(yīng)用啟動失敗時提供有關(guān)錯誤的詳細信息,這對于開發(fā)者來說非常有用,因為它可以幫助我們快速識別問題并找到解決方案,需要的朋友可以參考下2023-12-12詳解Java對象序列化為什么要使用SerialversionUID
這篇文章主要介紹了詳解Java對象序列化為什么要使用SerialversionUID,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11