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());
    }

 

posted @ 2019-05-08 15:25  c++天下第一  阅读(174)  评论(0编辑  收藏  举报