zoukankan      html  css  js  c++  java
  • 021.12 IO流 ObjectStream对象序列化

    内容:通过文件存储对象
    我们遇到的问题,需要保存对象到硬盘中,如何解决
    这个就是用来解决的

    用法:
    1、创建流对象FileOutputstream
    2、创建ObjectOutputStream对象与FileOutputStream关联
    3、使用writeObject方法写入对象,或者通过readObject读取对象
    对象要求继承Serializable接口,该接口为类提供一个序列号,用于读取的时候相对应,保证不出错,显示该序列号

    具体如下代码:

    //ObjectStreamDemo.java

    public static void main(String[] args) throws IOException
    {
        writeObj();
    }

    ##写入到硬盘,序列化

    private static void writeObj() throws IOException
    {
        //1、明确存储对象的文件
        FileOutputStream fos = new FileOutputStream("myfile\obj.object");
        //2、给操作文件对象加入写入对象功能
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        
        //3、调用写入对象的方法
        oos.writeObject(new Person("xx",21));
        
        //关闭
        oos.close();
    
    }

    ##读取,反序列化
    private static void readObject() throws IOException, ClassNotFoundException
    {
        //定义流对象关联存储文件
        FileInputStream fis = new FileInputStream("myfile\obj.object");
        
        //创建读取对象的功能流对象
        ObjectInputStream ois = new ObjectInputStream(fis);
        
        //读取对象
        Person p = (Person)ois.readObject();
        
        System.out.println(p.toString());
    }

    //Person.java
    public class Person implements Serializable
    {
        private static final long serialVersionUID = 3475857768779718900L;
        private String name;
        private int age;
        public Person() {
            super();
            // TODO 自动生成的构造函数存根
        }
        public Person(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        //get、set和toString方法省略。
    }




    注意:
    静态化的数据不会被序列化,某个数据不想序列化可以通过关键字transient修饰,瞬态

  • 相关阅读:
    LeetCode-Letter Combinations of a Phone Number
    LeetCode-Sort Colors
    C++Memset误区
    LeetCode-Valid Palindrome
    LeetCode-Longest Consecutive Sequence
    C++豆知识索引
    C++ 哈希表
    LeetCode-Sum Root to Leaf Numbers
    LeetCode-Word LadderII
    LeetCode-Word Ladder
  • 原文地址:https://www.cnblogs.com/-nbloser/p/9125609.html
Copyright © 2011-2022 走看看