Java 对象序列化和反序列化
2020-07-17 本文已影响0人
xiaogp
序列化(Serialization)是将对象的状态信息转化为可以存储或者传输的形式(字节序列)的过程,反序列化则为其逆过程.
序列化使用ObjectOutputStream下的writeObject方法
反序列化使用ObjectInputStream下的readObject方法
对于类对象只有实现了Serializable接口,它的对象才是可序列化的, 所以要用implements Serializable, 作为一个类可以被序列化的标识, Serializable本身是一个空接口
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class ObjectSerialization {
public static void main(String[] args) {
// 对Map进行序列化和反序列化
Map<String, Integer> map1 = new HashMap<>();
map1.put("a", 1);
map1.put("b", 2);
map1.put("c", 3);
Serialization(map1, "/data/test.dat");
Map<String, Integer> map2 = (Map) Deserialization("/data/test.dat");
System.out.println(map2);
System.out.println(map2.get("a"));
// 对类对象进行序列化和反序列化
Student2 student = new Student2("gp", 14);
student.getName();
Serialization(student, "/data/testClass.dat");
Student2 student2 = (Student2) Deserialization("/data/testClass.dat");
student2.getName();
}
/**
* 序列化
*
* @param object
* @param path
*/
public static void Serialization(Object object, String path) {
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));
objectOutputStream.writeObject(object);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 反序列化
*
* @param path
* @return
*/
public static Object Deserialization(String path) {
Object result = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path));
result = objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
class Student2 implements Serializable {
private final String name;
private final int age;
public Student2(String name, int age) {
this.name = name;
this.age = age;
}
public void getName() {
System.out.println(this.name);
}
}