序列化与反序列化
序列化:对象->文件 – ObjectOutputStream–序列化流
反序列化:文件->对象 – ObjectInputStream–反序列化流
序列化的思路:
1)需要准备要序列化的对象+序列化到哪里的目标文件的路径
2)序列化对象所在的类必须要实现序列化接口,不实现会报错
3)创建序列化流对象 OOS out = new OOS(new FOS(File/路径));
4)使用流进行对象的序列化输出 out.writeObject(s);
5)关流 out.close()
反序列化的思路:
1)前提:之前有序列化的数据,通过反序列化恢复成对象
2)序列化版本号必须一致,不一致就报错,最好一次序列化对应一次反序列化
3)创建反序列化流对象 OIS in = new OIS(new FIS(File/路径));
4)使用反序列化流恢复对象 Object o = in.readObject();
5)关流 in.close();
例题:
package cn.tedu.serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**本类用于测试序列化与反序列化*/
public class TestSerializable {
public static void main(String[] args) {
method();
method2();
}
//创建测试反序列化
private static void method2() {
ObjectInputStream in=null;
try {
in=new ObjectInputStream(new FileInputStream("D:\\1.txt"));
Object o=in.readObject();
System.out.println(o);
}catch (Exception e){
e.printStackTrace();
}finally {
try{
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
//创建测试序列化
private static void method() {
ObjectOutputStream out=null;
try {
//ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("D:\\1.txt"));
out=new ObjectOutputStream(new FileOutputStream("D:\\1.txt"));
Student s=new Student("小明","南京",'男',3);
out.writeObject(s);
}catch (Exception e){
e.printStackTrace();
}finally {
try{
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
Student代码:
package cn.tedu.serializable;
import java.io.Serializable;
import java.rmi.server.UID;
/**本类用于封装学生类*/
public class Student implements Serializable {
private static final long UID=1l;
private String name;
private String addr;
private char gender;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", addr='" + addr + '\'' +
", gender=" + gender +
", age=" + age +
'}';
}
public String getAddr() {
return addr;
}
public Student() {
System.out.println("无参构造");
}
public Student(String name, String addr, char gender, int age) {
this.name = name;
this.addr = addr;
this.gender = gender;
this.age = age;
System.out.println("全参构造");
}
public void setAddr(String addr) {
this.addr = addr;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
关于序列化版本号不一致报错的解决方案:
1.手动添加UID(指将UID的值写死,怎么样都不会变)可以任意序列化与反序列化
private static final long serialVersionUID = 1L;
2.不手动添加,自动生成,那就需要注意,每次编译都会生成一个新的UID
所以一次序列化需要对应一次反序列化,如果更改了目标类(Student)类中的内容
一定要先序列化再反序列,不然就报错
private static final long serialVersionUID = -5933827000382710953L;