Java List序列化的實現

概述 
java中的序列化與反序列化都要求對象實現Serializable接口(其實就是聲明一下),而對於List這種動態改變的集合默認是不實現這個接口的,也就是不能直接序列化。可是數組是能夠序列化的,因此咱們只須要將List集合與數組進行轉換就能夠實現序列化與反序列化了。java

序列化

Object對象數組

public class TestObject implements Serializable{

    private String name;
    private String address;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

}

實例化對象,加點數據,而後執行序列化工具

反序列化

public class Test {

    public static void main(String[] args) 
    {
        File file = new File("object.adt");
        try (ObjectInputStream out = new ObjectInputStream(new FileInputStream(file)))
        {
            //執行反序列化讀取
            TestObject[] obj = (TestObject[]) out.readObject();
            //將數組轉換成List
            List<TestObject> listObject = Arrays.asList(obj);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        }
    }
}

封裝

利用泛型把序列化和反序列化的方法封裝起來,方便使用。this

工具類

public class StreamUtils {

    /**
     * 序列化,List
     */
    public static <T> boolean writeObject(List<T> list,File file)
    {
        T[] array = (T[]) list.toArray();
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) 
        {
            out.writeObject(array);
            out.flush();
            return true;
        }
        catch (IOException e) 
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 反序列化,List
     */
    public static <E> List<E> readObjectForList(File file)
    {
        E[] object;
        try(ObjectInputStream out = new ObjectInputStream(new FileInputStream(file))) 
        {
            object = (E[]) out.readObject();
            return Arrays.asList(object);
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        }
        return null;
    }
}

使用工具類

//序列化
StreamUtils.<TestObject>writeObject(list, new File("object.adt"));
//反序列化
List<TestObject> re = StreamOfByte.<TestObject>readObjectForList(new File("object.txt"));
相關文章
相關標籤/搜索