1. Questions:

If I want to write an object to a file, but find that the byte stream and character stream cannot meet the requirements, how to write an object to a file? If you use a byte character stream, you have to convert an object to a byte/character and write it to a file, but there’s no way to convert an object to a byte in a byte character stream. How do you do that?

Serialization and deserialization

Java serialization: The process of turning objects into bytes, which is exactly what I need. Java deserialization: The process of restoring bytes to objects. This allows us to write and read objects from files

Use scenarios for serialization and deserialization

  • A. Write objects to hard disks.

  • B, Network transmission \

    • When transmitting text, audio, video and so on over the network, all are converted into binary sequence transmission, we want to transmit objects over the network, we must use serialization and deserialization to meet the requirements of sending and receiving data. First, to achieve data persistence, through the serialization of data permanently stored in the local hard disk; Second, to achieve remote network communication, the use of serialization, so that the object can be transmitted on the network byte sequence.

How to implement serialization and deserialization

5.1 implement Serializable interface

The Serializable interface has no methods, just an identifier that tells the Java mechanism that the class can be serialized; If not, the Java mechanism will automatically create one. SerialVersionUID is a 64-bit hash field based on the class name, interface name, member methods, properties, and so on.

  • If there is no SerialVersionUID, usually we will find that if the class’s attributes are modified after serialization, an error will be reported in the process of de-ordering. Because the attributes are modified, Java mechanism will create a new SerialVersionUID, which will be inconsistent with the original ID, and the deserialization will fail. \

    • If the implementation SerialVersionUID is set to ensure version compatibility, serialization and deserialization can still be performed even if an attribute or method is added, but the value of the newly added attribute is null, or the value of the deleted attribute is not displayed.
package com.chb.test; import java.io.Serializable; Public class Student implements Serializable{// Serializable private static final Long serialVersionUID = 1; private String name; private int age; private String sex; public Student() { } public Student(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } @override public String toString() {return "Student{"} @override public String toString() {return "Student "; } /** setgetter ellipses... * /}Copy the code

5.2 ObjectOutputStream and ObjectInputStream

The Serializalable interface simply provides a representation of converting an object to a binary sequence, and restoring a binary sequence to an object are two methods provided by ObjectOutputStream and OjbectInputStream: WriteObject () and readObject ()

  • writeObject()
public static void write(Student s1) throws Exception {
        FileOutputStream fos = new FileOutputStream(filename);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(s1);
        oos.close();
}
Copy the code
  • readObject()
public static Student read() throws Exception { FileInputStream fis = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fis); Student stu = new Student(); // Deserialize with readeObject() stu= (Student) ois.readObject(); ois.close(); return stu; }Copy the code

6, transient

In some cases, we do not serialize sensitive fields, or members of a class reference type cannot be serialized, so we need to use transient to modify these members to prevent them from being serialized. For example, a bank account object that does not want to serialize the account amount. Modify the Student class above to make the sex property transient

transient private String sex;
Copy the code

reserialize

Student s1 = new Student("roase",19, "female "); write(s1);Copy the code

Deserialization, read the object found :sex is null, indicating that the transient modified attribute will not be serialized.

6.1 defaultWriteObject and defaultReadObject ()

For the transient member age above, if we want to serialize and deserialize it here, how do we do it:

  • 1, remove transient decoration
  • 2. Provide two methods
    private void writeObject(ObjectOutputStream out) throws Exception{
        out.defaultWriteObject();
        out.writeInt(age);
    }
    private void  readObject(ObjectInputStream in) throws Exception {
        in.defaultReadObject();
        age=in.readInt();
    }
Copy the code

DefaultWriteObject () in ObjectOutputStream is first called in the writeObject() method, which implements the default serialization mechanism and ignores the age field. The writeInt() method is then called to explicitly write the age field to the ObjectOutputStream. ReadObject () reads objects in the same way as writeObject(). Executing the read() application again produces the following output: