1、被序列化/发布序列化操作的对象,需要实现 Serializable 接口
2、最好添加 private static final long serialVersionUID = 1L; 用于标记对象的版本
3、代码演示
package org.zln.seri; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; /** * Created by sherry on 16/9/18. */ public class Person implements Serializable{ private static final long serialVersionUID = 1L; private String name; private int age; @Override public String toString() { return new ToStringBuilder(this) .append("name", name) .append("age", age) .toString(); } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package org.zln.seri; import org.junit.Test; import java.io.*; import java.util.UUID; import static org.junit.Assert.*; /** * Created by sherry on 16/9/18. */ public class PersonTest { private void writeObj(){ String id = UUID.randomUUID().toString(); Person person = new Person("张柳宁_"+id,27); try { File file = new File("person_"+id); System.out.println("当前对象文件:"+file.getAbsolutePath()); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file)); objectOutputStream.writeObject(person); objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void readObj(){ writeObj(); File[] files = new File(".").listFiles(); for (File file:files){ if (file.getName().startsWith("person")){ try { ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file)); Person person = (Person) objectInputStream.readObject(); System.out.println(person); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } deleteObj(); } private void deleteObj() { File[] files = new File(".").listFiles(); for (File file : files) { if (file.getName().startsWith("person")) { file.delete(); System.out.println("删除:" + file.getAbsolutePath()); } } } }