概述
java中的序列化與反序列化都要求對象實現Serializable
接口(其實就是聲明一下),而對於List這種動態改變的集合默認是不實現這個接口的,也就是不能直接序列化。但是數組是可以序列化的,所以我們只需要將List集合與數組進行轉換就可以實現序列化與反序列化了。
序列化
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) { //創建要序列化的集合對象 List<TestObject> list = new ArrayList<>(); //加數據 for (int i = 0; i < 5; i++) { TestObject testObject = new TestObject(); testObject.setName("MJJ-"+i); testObject.setAddress("HangZhou"); list.add(testObject); } File file = new File("object.adt"); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) { //將List轉換成數組 TestObject[] obj = new TestObject[list.size()]; list.toArray(obj); //執行序列化存儲 out.writeObject(obj); } catch (IOException e) { e.printStackTrace(); } } }
反序列化
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(); } } }
封裝
利用泛型把序列化和反序列化的方法封裝起來,方便使用。
工具類
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"));