详解Java中的字节序列化与反序列化案例

原创 柔光的暖阳◎ 2024-11-30 10:42 95阅读 0赞

在Java中,字节序列化和反序列化是常见的对象持久化方式。下面详细讲解这两个过程的案例。

  1. 字节序列化(Serialization)

场景:一个Student类的对象student需要保存到磁盘。

代码:

  1. import java.io.*;
  2. // 定义一个Student类
  3. class Student {
  4. String name;
  5. int age;
  6. // 构造函数
  7. public Student(String name, int age) {
  8. this.name = name;
  9. this.age = age;
  10. }
  11. }
  12. public class SerializeExample {
  13. public static void main(String[] args) {
  14. // 创建一个学生对象
  15. Student student = new Student("Tom", 20);
  16. // 字节序列化为字节数组
  17. byte[] serializedStudent = serializeObject(student);
  18. System.out.println("Serialized Student: " + serializedStudent);
  19. // 反序列化恢复为对象
  20. Student deserializedStudent = deserializeObject(serializedStudent, Student.class));
  21. System.out.println("Deserialized Student: " + deserializedStudent);
  22. }
  23. // 字节序列化方法
  24. private static byte[] serializeObject(Object obj) {
  25. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  26. ObjectOutputStream oos = new ObjectOutputStream(bos);
  27. try {
  28. oos.writeObject(obj);
  29. oos.flush();
  30. return bos.toByteArray();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. return null;
  35. }
  36. // 反序列化方法
  37. private static Object deserializeObject(byte[] serializedObj, Class<?> clazz) {
  38. ByteArrayInputStream bis = new ByteArrayInputStream(serializedObj);
  39. ObjectInputStream ois = new ObjectInputStream(bis);
  40. try {
  41. return ois.readObject(clazz);
  42. } catch (IOException | ClassNotFoundException e) {
  43. e.printStackTrace();
  44. }
  45. return null;
  46. }
  47. }
  1. 字节反序列化(Deserialization)

场景:从磁盘读取字节数组,恢复为Student类的对象。

代码:

  1. // 从磁盘读取字节数组
  2. byte[] deserializedStudent = readFromFile("serialized_student.bin");
  3. // 将字节数组反序列化
  4. Student reconstructedStudent = deserializeObject(deserializedStudent, Student.class));
  5. System.out.println("Reconstructed Student: " + reconstructedStudent);

以上就是Java中字节序列化与反序列化的简单示例。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,95人围观)

还没有评论,来说两句吧...

相关阅读