虚拟化机制可以将对象转换成字节序列,这些字节序列可以保存在磁盘上
也可以在网络中传输,并允许程序将这些字节序列再次恢复成原来的对象
使用对象流Objectinputstream和ObjectOutputstream(处理流)
public static void main(String[] args) { testSerialize(); testDeserialize(); } public static void testSerialize(){ try ( ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:/DXl/FF.txt")) ){ oos.writeObject(new Car("djk","bu",34)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void testDeserialize(){ try ( ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:/DXl/FF.txt")) ){ System.err.println(ois.readObject()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } class Car implements Serializable{ private String brand; private String color; private int maxSpeed; public Car(String brand, String color, int maxSpeed) { System.out.println("Init Car"); this.brand = brand; this.color = color; this.maxSpeed = maxSpeed; } @Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", color='" + color + '\'' + ", maxSpeed=" + maxSpeed + '}'; }
序列化的目的是将对象中的数据(成员变量)转为字节序列,和成员方法无关
为了正确地序列化莫个对象,这个对象已经他所对应的类需要符合如下规则
public static void main(String[] args) { testSerialize(); testDeserialize(); } public static void testSerialize(){ try ( ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:/DXl/stu.txt")) ){ Teacher t=new Teacher("DJK"); Student s1=new Student("DXL",t); oos.writeObject(t); oos.writeObject(s1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void testDeserialize(){ try ( ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:/DXl/stu.txt")) ){ Teacher t= (Teacher) ois.readObject(); Student s1= (Student) ois.readObject(); System.out.println(t); System.out.println(s1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } class Teacher implements Serializable{ private String name; public Teacher(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return "Teacher{" + "name='" + name + '\'' + '}'; } public void setName(String name) { this.name = name; } } class Student implements Serializable{ private String name; private Teacher teacher; public Student(String name, Teacher teacher) { this.name = name; this.teacher = teacher; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", teacher=" + teacher + '}'; } }