Serialization and deserialization of Java

Posted by guanche on Thu, 02 Sep 2021 04:12:39 +0200

1. Serialization and deserialization

Java provides a mechanism for object serialization
An object can be represented by a byte sequence: the byte sequence contains the data of the object, the type of the object and the attributes stored in the object
      After the byte sequence is written out to the file, it is equivalent to persisting the information of an object in the file
On the contrary, the byte sequence can also be read back from the file, reconstruct the object and deserialize it
      The data of the object, the type of the object and the stored properties of the object can be used to create objects in memory
ObjectOutputStream   And   ObjectInputStream

2.ObjectOutputStream class

      Overview: java.io.ObjectOutputStream class is a subclass of OutputStream
      Features: Java objects can be stored in files in the form of bytes to realize the persistent storage of objects
      Construction method:
              - public ObjectOutputStream(OutputStream out): creates an ObjectOutputStream that specifies an OutputStream
      Member method:
              - public final void writeObject(Object obj): writes out the specified object
      Requirement: the class of the object to be serialized must implement the serialization interface

Create a student class

public class Student implements Serializable {
    public String name ;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Create a test class

public class Tests {
    public static void main(String[] args) throws IOException {

        // Requirement: write the Student object to the specified file
        // 1. Create Student object
        Student s = new Student("Zhang San",19);
        // 2. Create a serialized stream object and associate the destination file path
        FileOutputStream fos = new FileOutputStream(str);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        // 3. Write out the object
        oos.writeObject(s);
        System.out.println(s);
        // 4. Close the flow
        oos.close();
    }

    static String str = "day13_Properies class&Buffer stream&Conversion flow&Serialized stream&Decorator mode&commons-io tool kit\\resources\\b.txt";
}

3.ObjectInputStream class

          Overview: java.io.ObjectInputStream is a subclass of InputStream
          Features: the byte data of the object in the file can be reconstituted into an object
          Construction method:
              - public ObjectInputStream(InputStream in): creates an ObjectInputStream of a specified InputStream
          Member method:
              - public final Object readObject(): Refactoring objects

public class Tests {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        // Requirements: reconstruct the Student object in s.txt file

        // 1. Create a deserialization stream object and associate the destination path
        FileInputStream fis = new FileInputStream(str);
        ObjectInputStream bis = new ObjectInputStream(fis);
        // 2. Read / reconstruct objects
        Student s  = (Student) bis.readObject();
        System.out.println(s);
        // 3. Close the flow
        bis.close();
    }


    static String str = "day13_Properies class&Buffer stream&Conversion flow&Serialized stream&Decorator mode&commons-io tool kit\\resources\\b.txt";
}

4. Precautions for serialization 1:

1. This class (Student) must implement the import java.io.Serializable interface, which is a tag interface
        Classes that do not implement this interface will not serialize or deserialize [any state], and an exception will be thrown: java.io.NotSerializableException
2. All properties of this class must be serializable

Create a student class

public class Student implements Serializable {
    public String name ;
    // Do not serialize the attribute age, use transient keyword: transient state [transient]
    public transient int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Tests{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Test class 1

public class Tests1 {
    public static void main(String[] args) throws IOException {
        // Requirement: write out the Student object to the file
        // 1. Create Student object
        Student student = new Student("Zhang San",20);
        // 2. Create a serialized stream object and associate the destination file path
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(str));
        // 3. Write out the object
        oos.writeObject(student);
        // 4. Close the flow
        oos.close();
    }

    static String str = "day13_Properies class&Buffer stream&Conversion flow&Serialized stream&Decorator mode&commons-io tool kit\\resources\\b.txt";
}

Test class 2

public class Tests2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Requirements: reconstruct the Student object in s.txt file

        // 1. Create a deserialization stream object and associate the destination path
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(str));
        // 2. Read / reconstruct objects
        Student s = (Student) ois.readObject();
        System.out.println(s);
        // 3. Close the flow
        ois.close();
    }

    static String str = "day13_Properies class&Buffer stream&Conversion flow&Serialized stream&Decorator mode&commons-io tool kit\\resources\\b.txt";
}

5. Precautions for deserialization 2:

      1. For an object that can be deserialized by the JVM, it must be a class that can find the class file
          If the class file of the class cannot be found, an exception java.lang.ClassNotFoundException is thrown
      2. When the JVM deserializes the object, the class file can be found, but the class file has been modified after serializing the object
          Then, the deserialization operation will also fail and throw an exception: java.io.InvalidClassException
              Solution: add a version number in the class static final long serialVersionUID = 100L;

Student class

public class Student implements Serializable {
    static final long serialVersionUID = 100L;
    public String name ;
    public int age;
    public String sex;

    public Student(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

Test class 1

public class Tests {
    public static void main(String[] args) throws IOException {

        // Requirement: write out the Student object to the file
        // 1. Create Student object
        Student s = new Student("Zhang San",18,"male");
        // 2. Create a serialized stream object and associate the destination file path
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(str));
        // 3. Write out the object
        oos.writeObject(s);
        // 4. Close the flow
        oos.close();


    }

    static String str = "day13_Properies class&Buffer stream&Conversion flow&Serialized stream&Decorator mode&commons-io tool kit\\resources\\b.txt";
}

Test class 2

public class Tests2 {
    // Requirements: reconstruct the Student object in s.txt file
    static String str = "day13_Properies class&Buffer stream&Conversion flow&Serialized stream&Decorator mode&commons-io tool kit\\resources\\b.txt";
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 1. Create a deserialization stream object and associate the destination path
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(str));
        // 2. Read / reconstruct objects
        Student s = (Student) ois.readObject();
        System.out.println(s);

        ois.close();
    }
}

6. Case demonstration

Requirements:
      1. Serialize the collection containing multiple custom objects and save it to list.txt
      2. Deserialize list.txt, traverse the collection, and print object information

Student class

public class Students implements Serializable {

    public String name;
    public int age;

    public Students() {
    }

    public Students(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Students{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Test class

public class Tests {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        FileOutputStream fos = new FileOutputStream(str);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        ArrayList<Students> list = new ArrayList<>();
        list.add(new Students("Zhang San",20));
        list.add(new Students("Li Si",18));
        list.add(new Students("Wang Wu",32));
        oos.writeObject(list);


        FileInputStream fis = new FileInputStream(str);
        ObjectInputStream ois = new ObjectInputStream(fis);

        ArrayList<Students> list1 = (ArrayList<Students>) ois.readObject();
        for (Students students : list1) {
            System.out.println(students);
        }

        ois.close();
        oos.close();

    }

    static String str = "day13_Properies class&Buffer stream&Conversion flow&Serialized stream&Decorator mode&commons-io tool kit\\resources\\list.txt";
}

Topics: Java html5