/* * 1、java.io.NotSerializableException * 2、参与序列化和反序列化的对象,必须事先Serializable接口 * 3、注意:通过源代码发现,Serializable接口是一个标志接口 * 这个接口当中什么代码都没有 * 那么它的作用是什么呢? * 起到标识的作用,标志的作用,jvm看到这个类实现了这个接口,可能会给这个类进行特殊待遇*/
事先准备一个Student类:
这里要注意序列化类继承Serializable接口,不然会抛出:java.io.NotSerializableException
package com.bjpowernode.javase.day27.IO; /*序列化*/ import java.io.Serializable; public class Student implements Serializable { String name; int age; public Student(String name, int age) { this.name = name; this.age = age; } public Student() { } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
这里的FileInputStream构造方法中填了“true”,但是对读取序列化结果没有影响
如果要序列化多个对象,将对象放到集合里面就可以了
编写测试类:
public class ObjectOutputStreamTest01 { public static void main(String[] args) { //创建java对象 Student s1=new Student("zhangsan",123); //序列化 ObjectOutputStream oos= null; ObjectInputStream ois=null; try { oos = new ObjectOutputStream(new FileOutputStream("D:/javaSE/Test/Serializable.txt",true)); oos.writeObject(s1); ois=new ObjectInputStream(new FileInputStream("D:/javaSE/Test/Serializable.txt")); Object o1=ois.readObject(); System.out.println(o1); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { oos.flush(); } catch (IOException e) { e.printStackTrace(); } try { oos.close(); } catch (IOException e) { e.printStackTrace(); } try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } }