[JavaStudy] 6. 직렬화 ? 역직렬화 ? (2)

10925 단어 JavaStudyJavaStudy

Java 직렬화 예제 코드

기본(primitive) 타입java.io.Serializable 인터페이스를 상속받은 객체는 직렬화 할 수 있는 기본 조건을 갖는다.

Member.java 코드

import java.io.Serializable;

public 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);
    }
}

ObjectSerializableExam.java 코드

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;

public class ObjectSerializableExam {

  public static void main(String[] args) throws IOException, ClassNotFoundException {
    Member member = new Member("임준영",  "[email protected]", 30);
    byte[] serializedMember;
    
    // 직렬화
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    
    oos.writeObject(member);
    
    // 직렬화된 member 객체
    serializedMember = baos.toByteArray();

    // base64로 인코딩한 문자열
    String base64Member = Base64.getEncoder().encodeToString(serializedMember);

    // base64로 디코딩한 문자열
    byte[] deserializedMember = Base64.getDecoder().decode(base64Member);


    // 역직렬화
    ByteArrayInputStream bais = new ByteArrayInputStream(deserializedMember);
    ObjectInputStream ois = new ObjectInputStream(bais);

    Object objectMember = ois.readObject();

    Member readMember = (Member) objectMember;
    System.out.println(member);
    
  }
}

[결과]


출처 : https://velog.io/@sa1341/Java-%EC%A7%81%EB%A0%AC%ED%99%94%EB%A5%BC-%ED%95%98%EB%8A%94-%EC%9D%B4%EC%9C%A0%EA%B0%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C

좋은 웹페이지 즐겨찾기