zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    

      

  • 相关阅读:
    mysql生成随机时间
    使用JEECG心得
    嵌入式linux------ffmpeg移植 解码H264(am335x解码H264到yuv420并通过SDL显示)
    svn 的使用(二)
    Java的几个有用小Util函数(日期处理和http)
    设置UITableViewCell高度的问题
    初探排序学习笔记
    从串口设置、读取、并分析um220模块的数据
    NYOJ-47 过河问题
    Lock_sga 和 pre_page_sga 参数详解
  • 原文地址:https://www.cnblogs.com/leigepython/p/9996405.html
Copyright © 2011-2022 走看看