溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java如何實現(xiàn)序列化

發(fā)布時間:2020-06-12 19:34:38 來源:億速云 閱讀:109 作者:鴿子 欄目:編程語言

1、實現(xiàn)序列化:

1)使用Serializable接口實現(xiàn)序列化

首先我們定義一個對象類User

public class User implements Serializable {
    //序列化ID
    private static final long serialVersionUID = 1L;
    private int age;
    private String name;
    //getter和setter方法、
    //toString方法}

接下來,在Test類中去實現(xiàn)序列化和反序列化。

public class Test {
    public static void main(String[] args) throws Exception, IOException {
        //SerializeUser();
        DeSerializeUser();
    }
    //序列化方法
    private static void SerializeUser() throws FileNotFoundException, IOException {
        User user = new User();
        user.setName("Java的架構(gòu)師技術(shù)棧");
        user.setAge(24);
        //序列化對象到文件中
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("G://Test/template"));
        oos.writeObject(user);
        oos.close();
        System.out.println("序列化對象成功");
    }
    //反序列化方法
    private static void DeSerializeUser() throws FileNotFoundException, IOException{
        File file = new File("G://Test/template");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        User newUser = (User)ois.readObject();
        System.out.println("反序列化對象成功"+newUser.toString());
    }}

2)使用Externalizable接口實現(xiàn)序列化

首先,定義一個User1類

public class User1 implements Externalizable{
    private int age;
    private String name;
    //getter、setter
    //toString方法
    
    public User1() {}
    
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
    }
    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    }}

Externalizable和Serializable接口的區(qū)別:

1)Externalizable繼承自Serializable接口

2)需要我們重寫writeExternal()與readExternal()方法

3)實現(xiàn)Externalizable接口的類必須要提供一個public的無參的構(gòu)造器。

2、作用:

1)序列化就是一種用來處理對象流的機制,所謂對象流也就是將對象的內(nèi)容進行流化,可以對流化后的對象進行讀寫操作,也可以將流化后的對象傳輸與網(wǎng)絡(luò)之間;

2)為了解決對象流讀寫操作時可能引發(fā)的問題(如果不進行序列化,可能會存在數(shù)據(jù)亂序的問題)

3)序列化除了能夠?qū)崿F(xiàn)對象的持久化之外,還能夠用于對象的深度克隆

3、序列化的使用場景

1)永久性保存對象,保存對象的字節(jié)序列到本地文件或者數(shù)據(jù)庫中;

2)通過序列化以字節(jié)流的形式使對象在網(wǎng)絡(luò)中進行傳遞和接收;

3)通過序列化在進程間傳遞對象;

以上就是java實現(xiàn)序列化的方法的詳細內(nèi)容,更多請關(guān)注億速云其它相關(guān)文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI