Java的序列化和反序列化
package com.IO;
//自定义类:序列化
import java.io.*;
//Serializable必须调用他的String中的接口;否者序列号异常==重点
public class Demo02 implements Serializable {
//serialVersionUID为java序列号;用于反序列话识别==重点
public static final long serialVersionUID = 12L;
private String name;
private double hight;
public Demo02(String name, double hight) {
this.name = name;
this.hight = hight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHight() {
return hight;
}
public void setHight(double hight) {
this.hight = hight;
}
@Override
public String toString() {
return "Demo02{" +
"name='" + name + '\'' +
", hight=" + hight +
'}';
}
public Demo02() {
}
}
class Demo03{
public static void main(String[] args) throws IOException {
Demo02 demo02 = new Demo02("小茹",160.5);
File file =new File("D://IDEA/Demo.txt");
FileOutputStream fileOutputStream =new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(demo02);
objectOutputStream.close();
}
}
进行反序列化
- 序列号内部类的对象必须是Serializable;有序列化标识
- 常量可以使用;引用数据类型String是序列号
- 用Static,transient修饰的属性不可序列化;transient为了保护密码;防止序列化引用
package com.IO;
import java.io.*;
public class Test011 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
File file = new File("D://IDEA/Demo.txt");
FileInputStream fileInputStream =new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Object o = objectInputStream.readObject();
System.out.println(o);
}
}