Input / output stream and file operation 06: object serialization stream and deserialization stream and how to judge that the object stream has been read to the end

1, Object serialization stream

ObjectOutputStream writes the original data type and graphics of Java objects to OutputStream. You can use ObjectInputStream to read (refactor) objects. Persistent storage of objects can be achieved by using streaming files. If the stream is a network socket stream, you can refactor the object on another host or in another process.

ObjectOutputStream:
Construction method: ObjectOutputStream(OutputStream out)Create a write to the specified OutputStream of ObjectOutputStream. 
Serialize object method: writeObject(Object obj) Writes the specified object to the ObjectOutputStream. 
package Object serialization stream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;


public class ObjectOutputStreamDemo {

    public static void main(String[] args) throws IOException {
        //
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\IDEA\\IO flow\\Student information.txt"));
        //create object
        StudentDemo s = new StudentDemo("Shi xuhao", 20);
        oos.writeObject(s);

        //release
        oos.close();

    }
}

2, Object deserialization stream

To serialize or deserialize objects, you must implement the Serializable interface

Reason for deserialization failure: the original class has been changed, and the file of the class has changed. There are two or more classes with the same name in a project
Solution: set UID
private static final long serialVersionUID=42L;

package Object serialization stream;

import java.io.Serializable;

//To implement serialization or deserialization, the class must implement this interface
public class StudentDemo implements Serializable {

    //Set serialization ID,
    //After the serialization id is set and the class is changed, it can still be serialized without failure
    //
    private static final long serialVersionUID=42L;
    String name;
    int id;
    transient int age;//Does not participate in the serialization process

    public StudentDemo() {
    }

    public StudentDemo(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }
}

3, How to judge whether the object stream has been read to the end

Author: Huang shaocun, senior lecturer of kowtow dinglang. connect: https://blog.csdn.net/wolfcode_cn/article/details/80701035

For those who have used the object stream, it is clear that the object stream operates on objects. Objects stored one by one can only be read one by one. However, there is a problem that you can only read as many as you write. There is no judgment method to read to the end. If the reading exceeds, an exception java.io.EOFException will be thrown, How can we judge whether it is the last one if we want to be general?

Method 1

Convert multiple original objects into a collection object, and then obtain data from the collection object

@Test
public void testObjectOutputStream() throws Exception {
    ObjectOutputStream ojbOs = new ObjectOutputStream(new FileOutputStream(new File("user.obj")));
    // Storing objects with collections
    List<Student> list = new ArrayList<Student>();
    list.add(new Student("willie", 18));
    list.add(new Student("xiaoming", 18));
    // Write object
    ojbOs.writeObject(list);
    ojbOs.close();
}
 
@Test
public void testObjectInputStream() throws Exception {
    ObjectInputStream ojbIs = new ObjectInputStream(new FileInputStream(new File("user.obj")));
    // Read and fetch collection objects
    List<Student> list = (List<Student>)ojbIs.readObject();
    // Edit collection
    list.forEach(System.out::println);
    ojbIs.close();
}

Method 2

Method 1 is a better solution. If you don't want to convert to a collection object, you can also add a flag before or after the stored object. You can add an int value at the first position to record the number of stored objects, or you can add a null at the end to mark the end. See if you already know how to solve it. If you don't know yet! It's all right. Put on the code

@Test
    public void testObjectOutputStream2() throws Exception {
        ObjectOutputStream ojbOs = new ObjectOutputStream(new FileOutputStream(new File("student.obj")));
        // Write object
        ojbOs.writeObject(new Student("willie", 18));
        ojbOs.writeObject(new Student("xiaoming", 18));
        // Write a null object as the end identifier
        ojbOs.writeObject(null);
        ojbOs.close();
    }
 
    @Test
    public void testObjectInputStream2() throws Exception {
        ObjectInputStream ojbIs = new ObjectInputStream(new FileInputStream(new File("student.obj")));
        // Read and fetch collection objects
        Object obj = null;
        // Traverse the object until null is encountered
        while((obj = ojbIs.readObject()) != null){
            Student stu =(Student)obj;
            System.out.println(stu);
        }
 
        ojbIs.close();
    }

Method 3

Use the exception handling method. This is very simple. Just handle EOFException directly. When EOFException is encountered, it means that it has been read to the end

public void testObjectInputStream3() throws Exception {
    ObjectInputStream ojbIs = new ObjectInputStream(new FileInputStream(new File("student.obj")));
    List<Student> list = new ArrayList<>();
    try {
        // read object
        while(true){
            Student stu = (Student)ojbIs.readObject();
            list.add(stu);
        }
    } catch (Exception e) {
        // Operation after reading
        System.out.println(list);
    }
    ojbIs.close();
}

Tags: Java

Posted on Sat, 02 Oct 2021 21:12:25 -0400 by ch3m1st