一、说明
序列化与反序列化是什么
二、理解
序列化过程
整个过程是 JVM 独立的,序列化的对象可以在不同的平台上反序列化该对象
对象序列化,类必须实现Serializable接口
该类的所有属性必须是可序列化的,如果有一个属性不是可序列化的,则该属性必须注明是短暂的
使用 IO 流中的对象流实现序列化操作,将对象保存到文件,再读取出来
当序列化一个对象到文件时, 按照 Java 的标准约定是给文件一个 .ser 扩展名
序列化作用
对象转化为二进制,可用于网络传输
把内存中的对象保存到一个文件中或者数据库中
三、实现
1.实现接口
创建一个Student类,实现Serializable接口
public class Student implements java.io.Serializable { public String name; public String classes; public transient int SSN; public int number; public void checkInfo() { System.out.println("Student Info " + name + " " + classes); }}
复制代码
2.序列化方法
用ObjectOutputStream类 .writeObject()方法
FileOutputStream fileOut = new FileOutputStream("file\\student.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(s); out.close(); fileOut.close();
复制代码
public class SerializeDemo { public static void main(String [] args){ Student s = new Student(); s.number = 17; s.name = "Good"; s.classes = "computer_1"; s.SSN = 233; try { FileOutputStream fileOut = new FileOutputStream("file\\student.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(s); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in file/student.ser"); }catch(IOException i) { i.printStackTrace(); } }}
复制代码
3.反序列化方法
用ObjectInputStream类 .readObject()方法
FileInputStream fileIn = new FileInputStream("file\\student.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); s= (Student) in.readObject(); in.close(); fileIn.close();
复制代码
public class DeserializeDemo { public static void main(String [] args) { Student s = null; try { FileInputStream fileIn = new FileInputStream("file\\student.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); s= (Student) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Student class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Student"); System.out.println("Name: " + s.name); System.out.println("Address: " + s.classes); //SSN属性是短暂的,该值没有被发送到输出流,反序列化后属性为 0 System.out.println("SSN: " + s.SSN); System.out.println("Number: " + s.number); }}
复制代码
评论