Object serialization control input and output

What is object serialization

public interface Serializable {
}

serialize

public ObjectOutputStream (OutputStream out)

//Create an objectoutputstream output stream objectoutputstream OOS = new objectoutputstream (New fileoutputstream ("object. TXT");

//Output a person object to the output stream OOS writerObject(per);

Example 1

import java.io.Serializable;

public class Person implements Serializable {
    private String name;
    private int age;

    // 注意此处没有提供无参数的构造器
    public Person(String name,int age) {
        System.out.println("有参数的构造器");
        this.name = name;
        this.age = age;
    }
    // 省略 name 和 age的setter和getter方法
    ...
}
public class WriteObject {
    public static void main(String[] args) throws Exception {
        // 创建一个 ObjectOutputStream 输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
        Person per = new Person("C语言中文网",7);
        // 将 Per对象写入输出流
        oos.writeObject(per);
    }
}

Deserialization

public ObjectInputStream(InputStream out)

//Create an objectinputstream input stream objectinputstream OIS = new objectinputstream (New FileInputStream ("object. TXT"));

//Read a Java object from the input stream and cast it to the person class person P = (person) ois readObject();

Example 2

public class ReadObject {
    public static void main(String[] args) throws Exception {
        // 创建一个ObjectInputStream输入流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));
        // 从输入流中读取一个 Java对象,并将其强制类型转换为Person类
        Person p = (Person) ois.readObject();
        System.out.println("名字为:" + p.getName() + "\n年龄为:" + p.getAge());
    }
}

Java serialization number

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>