1、基本概念
序列化:把内存对象转换为字节码的过程
反序列化:把字节码转换为内存对象的过程
2、实例
实体类:
import java.io.Serializable;
public class Animal implements Serializable{
private static final long serialVersionUID = -5809782578272943999L;
private String saySome;
private String name;
private String sex;
private int years;
public String getSaySome() {
return saySome;
}
public void setSaySome(String saySome) {
this.saySome = saySome;
}
public void say(){
System.out.println("你说啥:"+saySome);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
}
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TestSerial {
//序列化
public static void serialize(Animal animal)throws FileNotFoundException,IOException{
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("E:/Animal.txt")));
oo.writeObject(animal);
System.out.println("Animal对象序列化成功!");
oo.close();
}
//反序列化
public static void unserialize()throws FileNotFoundException,IOException, ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("E:/Animal.txt")));
Animal animal = (Animal) ois.readObject();
System.out.println("Person对象反序列化成功!");
System.out.println("动物名称:"+animal.getName()+"\n动物性别:"+animal.getSex()+"\n动物年龄:"+animal.getYears());
}
public static void main(String[] args) throws Exception {
Animal animal=new Animal();
animal.setName("狗");
animal.setSex("男");
animal.setYears(10);
serialize(animal);
unserialize();
}
}
3、注意问题
- 必须实现Serializable接口或Externalizable接口
- 必须要有serialVersionUID