I about me

[Final] Serialization 본문

Java

[Final] Serialization

ssungni 2024. 6. 14. 12:18

https://inpa.tistory.com/entry/JAVA-%E2%98%95-%EC%A7%81%EB%A0%AC%ED%99%94Serializable-%EC%99%84%EB%B2%BD-%EB%A7%88%EC%8A%A4%ED%84%B0%ED%95%98%EA%B8%B0

 

☕ 자바 직렬화(Serializable) - 완벽 마스터하기

자바의 직렬화 & 역직렬화 직렬화(serialize)란 자바 언어에서 사용되는 Object 또는 Data를 다른 컴퓨터의 자바 시스템에서도 사용 할수 있도록 바이트 스트림(stream of bytes) 형태로 연속전인(serial) 데

inpa.tistory.com

 

Serialization (직렬화)

//  객체를 저장할 때 바이너리 모드(이진 모드) 혹은 문자 스트림을 사용할 수 있다.

바이너리 모드 (ex) 0101...)   "직렬화" 문자 스트림 (ex) John, 30)   "문자 파일"
- 내부 표현을 그대로 표현할 수 있기 때문
- 데이터를 더 안전하게 저장할 수 있기 떄문
-  빠르게 데이터를 읽고 쓸 수 있기 때문
가독성과 편집의 용이성을 제공하지만,
성능과 보안 면에서 불리할 수 있음
객체를 직렬화하려면 해당 객체가 직렬화 가능해야함
즉, Serializable 인터페이스를 구현해야함
객체의 상태 문자 파일에 텍스트로 기록됨

 

  • 어떻게 직렬화할까?   FileOutputStream과 ObjectOutputStream 2가지 스트림 사용한다.
  • 왜?
    • FileOutputStream은 파일과 연결하는 "연결 스트림"으로 사용한다.
    • ObjectOutputStream은 객체와 연결되어 데이터를 체인처럼 잇는 "체인 스트림"으로 사용한다.
  • writeObject 메서드: 객체를 파일에 쓰는 메서드
  • 예시
    더보기
    // A --- C(chain) ---- B
    // A 객체 생성
    Person person = new Person("John", 30);
    
    // B = FileOutputStream(A)
    try (FileOutputStream fileOut = new FileOutputStream("person.ser");
    	// C = ObjectOutputStream(B) (** ObjectOutputStream을 사용하여 객체를 파일에 직렬화하여 저장)
         ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
         // 객체를 파일에 쓰는 메서드
        out.writeObject(person);
    ...

 

  • Serializable interface
    • 객체가 다른 객체와 구성 관계를 가짐
    • "구성된 객체"도 직렬화됨
    • 예시
class Member implements Serializable {
    private String name;
    private String email;
    private int age;

    public Member(String name, String email, int age) {
        this.name = name;
        this.email = email;
        this.age = age;
    }
    @Override
    public String toString() {
        return String.format("Member{name='%s', email='%s', age='%s'}", name, email, age);
    }
}
  public static void main(String[] args) throws IOException, ClassNotFoundException {
        Member member = new Member("김배민", "deliverykim@baemin.com", 25); // Model 객체
        String serialData = serializeTest(member); // 직렬화
        deSerializeTest(serialData);    // 역직렬화
    }
  • “transient” keyword
class Member implements Serializable {
    private transient String name;
    private String email;
    private int age;
 

 

Deserialization (직렬화) 

  • 바이너리 데이터를 다시 읽어들이기 // 즉, 다시 문자로 하기
  • ObjectInputStream 클래스
    • readObject()
  • 예외가 발생할 수 있음
  • 예시
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;

class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String username;
    private transient String password; // 이 필드는 직렬화되지 않음

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
}

public class DeserializationExample {
    public static void main(String[] args) {
        // 직렬화 과정
        User user = new User("john_doe", "12345");

        try (FileOutputStream fileOut = new FileOutputStream("user.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(user);
            System.out.println("객체가 직렬화되어 파일에 저장되었습니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 역직렬화 과정
        try (FileInputStream fileIn = new FileInputStream("user.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            User deserializedUser = (User) in.readObject();
            System.out.println("객체가 역직렬화되었습니다.");
            System.out.println("사용자 이름: " + deserializedUser.getUsername());
            System.out.println("비밀번호: " + deserializedUser.getPassword()); // null 출력
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
객체가 직렬화되어 파일에 저장되었습니다.
객체가 역직렬화되었습니다.
사용자 이름: john_doe
비밀번호: null

 

 

'Java' 카테고리의 다른 글

[Final] collections  (0) 2024.06.15
[Final] File I/O  (0) 2024.06.13
[Final] Exception Handling 문제 풀이  (0) 2024.06.11
[Final] Exception  (0) 2024.06.11
[Final] Interface  (0) 2024.06.10