JAVA Serializable 實例

1、什麼是序列化和反序列化
Serialization(序列化)是一種將對象以一連串的字節描述的過程;反序列化deserialization是一種將這些字節重建成一個對象的過程。

2、什麼情況下需要序列化
a)當你想把的內存中的對象保存到一個文件中或者數據庫中時候;
b)當你想用套接字在網絡上傳送對象的時候;
c)當你想通過RMI傳輸對象的時候;

3、如何實現序列化

將需要序列化的類實現Serializable接口就可以了,Serializable接口中沒有任何方法,可以理解爲一個標記,即表明這個類可以序列化。

原始api

public interface Serializable
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype’s public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class’s state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

//序列化對象進行輸出(轉化爲Object流)
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
//反序列化用到
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;

實例:(以存儲文件爲例)

創建序列化對象

package com.frank.serializable;

import java.io.Serializable;

public class People implements Serializable{
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public People(int id,String name){
        this.id = id;
        this.name = name;
    }

}

Test類:

package com.frank.serializable;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class SerializableTest {

    public static void seria(People people) throws IOException{

        ObjectOutputStream objectOutput=null;

        try {

            objectOutput=new ObjectOutputStream(new FileOutputStream("D:\\out.txt"));

            objectOutput.writeObject(people);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            System.out.println("we have serialized the object");
            objectOutput.flush();
            objectOutput.close();
        }


    }

    public static People deSeria() throws IOException{

        ObjectInputStream objectInputStream=null;

        People people=null;

        try {

            objectInputStream=new ObjectInputStream(new FileInputStream("D:\\out.txt"));

            people=(People)objectInputStream.readObject();

        } catch (Exception e) {
            // TODO: handle exception
        }finally{

            System.out.println(people.getId()+","+people.getName());

            objectInputStream.close();

        }
        return people;

    }


    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        People people = new People(21,"frank");

        SerializableTest.seria(people);

//      SerializableTest.deSeria();

    }

}

運行序列化對象,查看文件

這裏寫圖片描述

序列化對象輸出的爲字節 記事本打開亂碼 正常

反序列化:

這裏寫圖片描述

發佈了65 篇原創文章 · 獲贊 71 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章