1 package model; 2 3 import java.io.Serializable; 4 5 public class Person implements Serializable { 6 /** 7 * 序列化标记ID 8 */ 9 private static final long serialVersionUID = 1L; 10 private String name; 11 private int age; 12 13 public Person(String name, int age) { 14 super(); 15 this.name = name; 16 this.age = age; 17 } 18 19 public String getName() { 20 return name; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public int getAge() { 28 return age; 29 } 30 31 public void setAge(int age) { 32 this.age = age; 33 } 34 35 @Override 36 public String toString() { 37 return "name=" + name + ", age=" + age; 38 } 39 40 }
private static final long serialVersionUID = 1L;//这是序列化标记
当Person这个类中参数改变时候。多加入了一个属性时候,这个类将不能被序列化!
想要序列化的类必须实现Serializable接口。
其实这个接口是没有抽象方法的,其实就是起到标记的作用
-----------------------------------------------------------------------------------------------------------------------------------
1 package serialization_01; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.ObjectInputStream; 7 import java.io.ObjectOutputStream; 8 import java.text.MessageFormat; 9 10 import model.Person; 11 12 public class serialization_001 { 13 14 public static void main(String[] args) throws Exception { 15 serializationo1(); 16 Person person = overserializationo2(); 17 String format = MessageFormat.format("name={0},age={1}", person.getName(), person.getAge()); 18 System.out.println(format + "-------反序列化结束!"); 19 } 20 21 private static Person overserializationo2() throws Exception, Exception { 22 /** 23 * 反序列化 24 * 25 */ 26 27 ObjectInputStream oin = new ObjectInputStream(new FileInputStream("D:\\serializationo1.txt")); 28 Person person = (Person) oin.readObject();// 向下转型 29 return person; 30 31 } 32 33 public static void serializationo1() throws IOException, IOException { 34 /** 35 * 序列化 36 */ 37 Person person = new Person("张三", 12); 38 ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream("D:\\serializationo1.txt")); 39 oout.writeObject(person); 40 System.out.println("序列化完成"); 41 oout.close(); 42 43 } 44 45 }
原文:http://www.cnblogs.com/zr20160507/p/5572959.html