• java-IO处理类的序列化与反序列化


    package TestIo;
    
    import java.io.*;
    
    /**
     * 序列化
     *
     *
     * 对象序列化
     *
     * 一  创建对象 需要说明,想序列化的对象一定要是实现Serivalizable接口
     *
     * 二 将对象转为序列化对象
     *
     * 三 然后用这个对象写对象或者是读对角
     *
     * 四 如果写的话,则要flush 或者是close
     *
     *
     */
    public class Demo6 {
        public static void main(String[] args) {
    //        TestSerializable testSerializable = new TestSerializable();
            FanSerive fanSerive = new FanSerive();
        }
    }
    
    /**
     * 序列化的类一定要实现Serializable
     */
    class Person implements Serializable {
        // 添加序列化ID,它决定着是否能够成功反序列化!
        private static final long serialVersionUID = 1L;
        int age;
        boolean isMan;
        String name;
    
        public Person(int age, boolean isMan, String name) {
            super();
            this.age = age;
            this.isMan = isMan;
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Person [age=" + age + ", isMan=" + isMan + ", name=" + name + "]";
        }
    }
    
    /**
     * 执行序列化
     */
    class TestSerializable {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
    
            FileOutputStream fos = null;
            FileInputStream fis = null;
            ObjectOutputStream oos = null;
            ObjectInputStream ois = null;
            // 通过ObjectOutputStream将Person对象的数据写入到文件中,即序列化。
            Person person = new Person(18, true, "监控中心");
            // 声明写出对象
            fos = new FileOutputStream("d:/person.txt");
            // 将文件对象序列化
            oos = new ObjectOutputStream(fos);
            // 序列化的对象写内容
            oos.writeObject(person);
            oos.flush();
            oos.close();
        }
    }
    
    /**
     * 反序列化
     */
    class FanSerive {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            System.out.println("执行读取文件对象的内容");
            FileInputStream fileInputStream = new FileInputStream("d:/person.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Person person = (Person) objectInputStream.readObject();
            System.out.println(person);
        }
    }
    

      

  • 相关阅读:
    How much training data do you need?
    什么样的论文容易接收发表?​
    How to Write and Publish a Scientific Paper: 7th Edition(科技论文写作与发表教程)(11.04更新)
    如何起草你的第一篇科研论文——应该做&避免做
    Writing the first draft of your science paper — some dos and don’ts
    matlab学习笔记 bsxfun函数
    乘法器的Verilog HDL实现
    重构:改善既有代码的设计
    【Leetcode】Length of Last Word
    Saving HDU hdu
  • 原文地址:https://www.cnblogs.com/leigepython/p/9996405.html
Copyright © 2020-2023  润新知