好记性不如乱笔头。
今天说说反序列化吧,参考了网上的博客参考的博客
序列化:把对象转换为字节序列的过程称为对象的序列化。
反序列化:把字节序列恢复为对象的过程称为对象的反序列化。
package com.fx.style;
import java.io.Serializable;
/**
* 静态static的属性,不序列化。
* transient,不序列化。
* serialVersionUID 必须一致才能成功的反序列化
*/
public class FlyPig implements Serializable{
private static final long serialVersionUID = 1L;
private static String AGE = "220";
private String name;
private String color;
transient private String car;
public static String getAGE() {
return AGE;
}
public static void setAGE(String AGE) {
FlyPig.AGE = AGE;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
@Override
public String toString() {
return "FlyPig{" +
"AGE "+AGE+ '\'' +
"name='" + name + '\'' +
", color='" + color + '\'' +
", car='" + car + '\'' +
'}';
}
}
测试一波
“`
package com.fx.style;
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FlyPig f1 = serializeFlyPig();
FlyPig f2 = deserializeFlyPig();
System.out.println("-------------------------------");
System.out.println(f1);
System.out.println(f2);
System.out.println("-------------------------------");
System.out.println(f1==f2);
} catch (Exception e) {
e.printStackTrace();
}
}
private static FlyPig serializeFlyPig() throws Exception{
FlyPig flyPig = new FlyPig();
flyPig.setColor("黑色");
flyPig.setName("奥迪");
flyPig.setCar("0000");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("E:/flypig.txt")));
oos.writeObject(flyPig);
System.out.println("序列化对象成功");
oos.close();
return flyPig ;
}
/**
* 反序列化
*/
private static FlyPig deserializeFlyPig() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("E:/flypig.txt")));
FlyPig flyPig = (FlyPig) ois.readObject();
System.out.println("FlyPig 对象反序列化成功!");
return flyPig;
}
}
FlyPig 对象反序列化成功!
FlyPig{AGE 220’name=’奥迪’, color=’黑色’, car=’0000’}
FlyPig{AGE 220’name=’奥迪’, color=’黑色’, car=’null’}
false