概述
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"));