Serialization. Output a Java object as a byte array. By serializing it, you can write it to a file.
Serializable interfaceClasses that implement the Serializable interface can be serialized.
import java.io.Serializable;
public class Person implements Serializable {
    private String greeting = "hello";
    Person(String greeting) {
        this.greeting = greeting;
    }
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializeSample {
    public static void main(String[] args) {
        var person = new Person("hello");
        try {
            var objectOutputStream = new ObjectOutputStream(new FileOutputStream("person.txt"));
            objectOutputStream.writeObject(person);
            objectOutputStream.flush();
            objectOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
        Recommended Posts