- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- 深入理解Java序列化與反序列化
序列化:將對象轉換為二進(jìn)制序列在網(wǎng)絡(luò )中傳輸或保存到磁盤(pán)
反序列化:從網(wǎng)絡(luò )或磁盤(pán)中將二進(jìn)制序列轉換為對象
注意:
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; } }
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))) { //寫(xiě)入對象 out.writeObject(elephant); } catch (IOException e) { e.printStackTrace(); } } static Object read(){ //創(chuàng )建對象輸出流 try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) { //寫(xiě)入對象 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); } }
寫(xiě)入D盤(pán)的對象:
到此這篇關(guān)于深入理解Java序列化與反序列化的文章就介紹到這了,更多相關(guān)Java序列化與反序列化內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站