一、概念
序列化:将对象转换为字节序列的过程。
反序列化:将字节序列恢复为对象的过程。
二、简单示例
package serialization; import java.io.Serializable; public class Person implements Serializable { /**
* @Fields serialVersionUID : 自动生成的序列化id
*/ private static final long serialVersionUID = 903332120406898371L; private String name; //使用transient修饰,序列化时,将忽略该字段。
private transient String password; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }
Person类(被序列化的对象)
package serialization; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public final class SerializePerson { public void serPerson() throws IOException { Person p = new Person(); p.setName("Test");
p.setPassword("password"); File f = new File(".\\src\\serialization\\Person.out"); FileOutputStream fo = new FileOutputStream(f);
ObjectOutputStream oo = new ObjectOutputStream(fo); oo.writeObject(p);
oo.close(); System.out.println("Person对象序列化成功!");
} @SuppressWarnings("resource")
public Person deserPerson() throws Exception { File f = new File(".\\src\\serialization\\Person.out"); FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis); Person person = (Person) ois.readObject();
System.out.println("Person对象反序列化成功!");
return person; } }
序列化与反序列化方法
package serialization; public class Test { public static void main(String[] args) throws Exception { SerializePerson sp = new SerializePerson();
sp.serPerson();
Person p = sp.deserPerson(); System.out.println("name:" + p.getName() + ", password:"
+ p.getPassword());
}
}
测试类
使用 transient 修饰字段,序列化时将忽略该字段。