Serializable
Сериализация (Serialization) — это процесс, который переводит объект в последовательность байтов, по которой затем его можно полностью восстановить.
Пример:
public record Person(String name) implements Serializable {@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +'}';}}
public class Foo {public Path serialized(Object obj) throws IOException {Path filePath = Path.of(obj.getClass() + "_" + UUID.randomUUID().toString() + ".txt");OutputStream outputStream = Files.newOutputStream(Path.of(String.valueOf(filePath)));ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);objectOutputStream.writeObject(obj);objectOutputStream.close();return filePath;}public void deserialized(Path path) throws IOException, ClassNotFoundException {ObjectInputStream objectInputStream = new ObjectInputStream(Files.newInputStream(path));Object deserialized = objectInputStream.readObject();System.out.println(deserialized);Files.delete(path);}}
public class Main {public static void main(String[] args) throws IOException, ClassNotFoundException {Person person = new Person("Виталий");System.out.println(person);Foo foo = new Foo();Path path = foo.serialized(person);foo.deserialized(path);}}
Семинар Здесь