序列化与反序列化



序列化的原本意图是希望对一个Java对象作一下“变换”,变成字节序列,这样一来方便持久化存储到磁盘,避免程序运行结束后对象就从内存里消失,另外变换成字节序列也更便于网络运输和传播


  • 序列化:把Java对象转换为字节序列。

  • 反序列化:把字节序列恢复为原先的Java对象。


  • ObjectOutputStream是将一个对象写入文件:如果使用这个类写入对象,这个对象需要序列化(实现接口Serializable)

  • ObjectInputStream是从文件中读一个对象:反序列化






    public static void main(String[] args) throws IOException, ClassNotFoundException {
        serialize();
        deserialize();
    }

    //序列化
    public static void serialize() throws IOException {

        Student student = new Student();
        student.setName("kakafa");
        student.setAge( 18 );
        student.setScore( 100 );

        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream( new FileOutputStream( new File("student.txt") ) );
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            objectOutputStream.writeObject( student );
            objectOutputStream.close();
        }

        System.out.println("序列化成功!已经生成student.txt文件");
        System.out.println("==============================================");


    }

    //反序列化
    public static void deserialize(  ) throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream =
                new ObjectInputStream( new FileInputStream( new File("student.txt") ) );
        Student student = (Student) objectInputStream.readObject();
        objectInputStream.close();

        System.out.println("反序列化结果为:");
        System.out.println( student );
    }












java对象从一个系统传输到另一个系统后无法被反序列化的问题:https://blog.csdn.net/u011489186/article/details/119387642






参考链接:https://mp.weixin.qq.com/s/0EfIUB9E-0Oh_Clwuxswuw



posted @   卡卡发  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2021-07-07 继承Thread类
点击右上角即可分享
微信分享提示