zoukankan      html  css  js  c++  java
  • IO流之序列化

     类通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化,并抛出异常(NotSerializableException

    格式:

    public class 类名 implements Serializable{ }

    一,序列化对象

    ObjectOutputStream 继承于OutputStream,专门用于把对象序列化到本地。提供了

    writeXXX

    writeObject() 用于写入一个对象

    public static void main(String[] args) throws IOException {
            Student stu=new Student("001","张三",20);
            File file=new File("D:\111\a.txt");
            FileOutputStream out=new FileOutputStream(file);
            ObjectOutputStream oos=new ObjectOutputStream(out);
            oos.writeObject(stu);
            oos.close();
            out.close();
        }

    序列化之后文件内容就成这样了:

    二,反序列化对象

    ObjectInputStream 继承于InputStream ,专门用于把本地持久化内容反序列化到内存,提供了

    readXXX

    readObject() 用于读取一个序列化内容并返回一个对象

    把上面序列化的文件反序列化回来:

    public static void main(String[] args) throws IOException, ClassNotFoundException {
            
            //反序列化
            File file=new File("D:\111\a.txt");
            FileInputStream in=new FileInputStream(file);
            ObjectInputStream ois=new ObjectInputStream(in);
            Student student=(Student)ois.readObject();
            System.out.println(student);
            ois.close();
            in.close();
        }

    解决问题: 当序列化完成后,后期升级程序中的类(Student),此时再反序列化时会出现异常

    解决方案:(给这个类加个随机版本号就行了)

    public class Student implements Serializable {
        private static final long serialVersionUID = -1003763572517930507L;

    三,额外再补充一个数据流

    DataOutputStream/DataInputStream(特别适合读取/写入在网络传输过程中的数据流)

    DataOutputStream 继承OutputStream,专门用于把基本java数据类型写入输出流。提供了writeXXX 写入基本java数据类型

    写入:

    public static void main(String[] args) throws IOException, ClassNotFoundException {
            File file=new File("D:\111\a.txt");
            FileOutputStream out=new FileOutputStream(file);
            DataOutputStream dos=new DataOutputStream(out);
            dos.writeInt(1);
            dos.writeUTF("哈喽");
            out.close();
            dos.close();
        }

    DataInputStream 继承于InputStream,允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型

    读取:(顺序与写入的顺序要一致)

    public static void main(String[] args) throws IOException, ClassNotFoundException {
            File file=new File("D:\111\a.txt");
            FileInputStream in=new FileInputStream(file);
            DataInputStream dis=new DataInputStream(in);
            System.out.println(dis.readInt());
            System.out.println(dis.readUTF());
        }
  • 相关阅读:
    《图解HTTP》读书笔记
    【译】关于vertical-align你应知道的一切
    【移动端debug-5】可恶的1px万能实现方案
    《编写高质量代码改善JavaScript程序的188个建议》读书笔记
    【移动端debug-4】iOS下setTimeout无法触发focus事件的解决方案
    一张图看懂Function和Object的关系及简述instanceof运算符
    三张图搞懂JavaScript的原型对象与原型链
    一张图看懂encodeURI、encodeURIComponent、decodeURI、decodeURIComponent的区别
    图解call、apply、bind的异同及各种实战应用演示
    centos vm 桥接 --网络配置
  • 原文地址:https://www.cnblogs.com/zhangxiong-tianxiadiyi/p/10832106.html
Copyright © 2011-2022 走看看