详解Java中的字节序列化与反序列化案例
在Java中,字节序列化和反序列化是常见的对象持久化方式。下面详细讲解这两个过程的案例。
- 字节序列化(Serialization)
场景:一个Student类的对象student需要保存到磁盘。
代码:
import java.io.*;
// 定义一个Student类
class Student {
String name;
int age;
// 构造函数
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializeExample {
public static void main(String[] args) {
// 创建一个学生对象
Student student = new Student("Tom", 20);
// 字节序列化为字节数组
byte[] serializedStudent = serializeObject(student);
System.out.println("Serialized Student: " + serializedStudent);
// 反序列化恢复为对象
Student deserializedStudent = deserializeObject(serializedStudent, Student.class));
System.out.println("Deserialized Student: " + deserializedStudent);
}
// 字节序列化方法
private static byte[] serializeObject(Object obj) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
try {
oos.writeObject(obj);
oos.flush();
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 反序列化方法
private static Object deserializeObject(byte[] serializedObj, Class<?> clazz) {
ByteArrayInputStream bis = new ByteArrayInputStream(serializedObj);
ObjectInputStream ois = new ObjectInputStream(bis);
try {
return ois.readObject(clazz);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
- 字节反序列化(Deserialization)
场景:从磁盘读取字节数组,恢复为Student类的对象。
代码:
// 从磁盘读取字节数组
byte[] deserializedStudent = readFromFile("serialized_student.bin");
// 将字节数组反序列化
Student reconstructedStudent = deserializeObject(deserializedStudent, Student.class));
System.out.println("Reconstructed Student: " + reconstructedStudent);
以上就是Java中字节序列化与反序列化的简单示例。
还没有评论,来说两句吧...