SeouliteLab

[Java/자바] 직렬화(Serialize)와 역직렬화(Deserialize) 본문

프로그래밍

[Java/자바] 직렬화(Serialize)와 역직렬화(Deserialize)

Seoulite Lab 2024. 3. 8. 09:31

Java에서는 직렬화와 역직렬화를 통해 객체를 파일로 저장하거나 네트워크를 통해 전송할 수 있습니다. 직렬화는 객체를 바이트 스트림으로 변환하는 과정이며, 역직렬화는 바이트 스트림에서 객체를 다시 복원하는 과정입니다. 아래에서는 각각의 개념과 예제를 살펴보겠습니다.

1. 직렬화(Serialization)란?

직렬화는 객체를 바이트 스트림으로 변환하여 저장하거나 전송하기 위한 과정입니다. 이를 위해 객체는 java.io.Serializable 인터페이스를 구현해야 합니다.

import java.io.*;

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

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

public class SerializationExample {
    public static void main(String[] args) {
        Person person = new Person("John", 30);

        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            out.writeObject(person);
            System.out.println("직렬화 완료");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 역직렬화(Deserialization)란?

역직렬화는 직렬화된 바이트 스트림을 다시 객체로 변환하는 과정입니다. 직렬화된 객체는 Serializable 인터페이스를 구현해야 합니다.

import java.io.*;

public class DeserializationExample {
    public static void main(String[] args) {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person person = (Person) in.readObject();
            System.out.println("역직렬화 완료");
            System.out.println("이름: " + person.getName() + ", 나이: " + person.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

3. 직렬화와 역직렬화를 통한 객체 저장 및 복원

직렬화와 역직렬화를 통해 객체를 파일에 저장하고 다시 복원하는 예제입니다.

import java.io.*;

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

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class SerializationDeserializationExample {
    public static void main(String[] args) {
        Person person = new Person("Alice", 25);

        // 직렬화
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
            out.writeObject(person);
            System.out.println("직렬화 완료");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 역직렬화
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) {
            Person restoredPerson = (Person) in.readObject();
            System.out.println("역직렬화 완료");
            System.out.println("이름: " + restoredPerson.getName() + ", 나이: " + restoredPerson.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}