• Java学习笔记——序列化


    目录

    一、序列化相关概念

    二、序列化 & 反序列化


    一、序列化相关概念

    序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。

    整个过程都是 Java 虚拟机(JVM)独立的,也就是说,在一个平台上序列化的对象可以在另一个完全不同的平台上反序列化该对象。

    序列化的用途

    • 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;
    • 在网络上传送对象的字节序列。

    序列化的实现

    • java.io.ObjectOutputStream代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。只有实现了Serializable和Externalizable接口的类的对象才能被序列化。

    • java.io.ObjectInputStream代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们反序列化为一个对象,并将其返回。

    二、序列化 & 反序列化

    首先,我们先定义一个Student1对象类,之后再进行序列化和反序列化,相关代码如下:

    1. import java.io.*;
    2. class Student1 implements Serializable{
    3. public String name;
    4. public String sex;
    5. public int age;
    6. public float height;
    7. public float weight;
    8. public void Information() {
    9. System.out.println("name: " + name
    10. + ", sex: " + sex
    11. + ", age: " + age
    12. + ", height: " + height
    13. + ", weight: " + weight
    14. );
    15. }
    16. }
    17. public class Day37 {
    18. public static void main(String[] args) throws Exception, IOException{
    19. toSerialize();
    20. toDeserialize();
    21. }
    22. private static void toSerialize() throws FileNotFoundException, IOException {
    23. Student1 stu = new Student1();
    24. stu.name = "Jack";
    25. stu.sex = "man";
    26. stu.age = 18;
    27. stu.height = 188.0F;
    28. stu.weight = 80.0F;
    29. try {
    30. // 序列化到文件中
    31. FileOutputStream fileOut = new FileOutputStream("E:\\Java_project\\src\\Java_learning\\Student1.ser");
    32. ObjectOutputStream out = new ObjectOutputStream(fileOut);
    33. out.writeObject(stu);
    34. out.close();
    35. fileOut.close();
    36. System.out.println("序列化成功!");
    37. } catch (IOException i) {
    38. i.printStackTrace();
    39. }
    40. }
    41. private static void toDeserialize() throws FileNotFoundException, IOException{
    42. Student1 stu2 = null;
    43. try{
    44. FileInputStream filein = new FileInputStream("E:\\Java_project\\src\\Java_learning\\Student1.ser");
    45. ObjectInputStream in = new ObjectInputStream(filein);
    46. stu2 = (Student1)in.readObject();
    47. in.close();
    48. filein.close();
    49. System.out.println("反序列化成功!");
    50. }catch (IOException | ClassNotFoundException i){
    51. i.printStackTrace();
    52. }
    53. stu2.Information();
    54. }
    55. }
    1. 序列化成功!
    2. 反序列化成功!
    3. name: Jack, sex: man, age: 18, height: 188.0, weight: 80.0
  • 相关阅读:
    【网格黑科技】扒一扒你所不知道的Cast-Designer网格黑科技
    java毕业设计的电影社区网站mybatis+源码+调试部署+系统+数据库+lw
    和数集团首款自研虚拟数字人上线,“始祖龙”带你跨山海,链未来
    手把手教你搭建SpringCloud项目
    力扣28. 找出字符串中第一个匹配项的下标
    SpringMVC执行流程
    代码整洁之道-读书笔记之格式
    小程序容器助力车企抢滩智慧车载新生态
    【NSMutableDictionary Objective-C语言】
    「秋招」这份各大厂面试万金油手册,吃透保你进大厂
  • 原文地址:https://blog.csdn.net/weixin_45666660/article/details/126134836