App下載

學(xué)習(xí)Java序列化與反序列化 詳細(xì)案例解析

神仙女孩破破 2021-08-20 14:53:27 瀏覽數(shù) (2021)
反饋

一、前言

序列化:將對(duì)象轉(zhuǎn)換為二進(jìn)制序列在網(wǎng)絡(luò)中傳輸或保存到磁盤(pán)

反序列化:從網(wǎng)絡(luò)或磁盤(pán)中將二進(jìn)制序列轉(zhuǎn)換為對(duì)象

注意:

  • 對(duì)象必須實(shí)現(xiàn)Serializable接口

在這里插入圖片描述

  • 對(duì)象的所有屬性都要能序列化(Integer,Byte等都進(jìn)行了序列化)

1.1 String

在這里插入圖片描述

1.2 Integer

在這里插入圖片描述

二、案例

2.1 編寫(xiě)大象類(lèi)

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 大象測(cè)試類(lèi)

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))) {
           //寫(xiě)入對(duì)象
            out.writeObject(elephant);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static Object read(){
        //創(chuàng)建對(duì)象輸出流
        try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) {
            //寫(xiě)入對(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é)果

在這里插入圖片描述

寫(xiě)入D盤(pán)的對(duì)象:

在這里插入圖片描述

到此這篇關(guān)于Java序列化與反序列化的文章就介紹到這了,更多相關(guān)Java序列化與反序列化內(nèi)容,請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,也希望大家以后多多支持我們!


0 人點(diǎn)贊