Java

Serialization (직렬화)

예요 2024. 6. 28. 20:27

Serialization (직렬화)

  • 자바 시스템 내부에서 사용되는 객체 및 데이터를 외부 자바 시스템에서도 사용할 수 있도록 바이트 형태로 데이터를 변환하는 기술(직렬화) + 바이트로 변환된 데이터를 다시 객체로 변환하는 기술(역직렬화)
  • JVM 메모리에 상주(힙 또는 스택)되어 있는 객체 데이터를 바이트 형태로 변환하는 기술 + 직렬화된 바이트 형태의 데이터를 객체로 변환하여 JVM으로 상주시키는 형태
  • 클래스를 파일에 읽히고 쓸 수 있도록 하거나 다른 서버로 보내고 받도록 하기 위해서 구현해야 한다.

① Serialization 구현

 

public class SerialUser implements Serializable {

    static final long serialVersionUID = 55555L;

    private int id;
    private String name;

    SerialUser(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "{ id : " + id + ", name : " + name + " }";
    }

}

 

public class Serial {

    public void saveObject(String filePath, SerialUser user) {

        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {

            fos = new FileOutputStream(filePath);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(user);
            System.out.println("Finish Write");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {

            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }

    }

    public void loadObject(String filePath) {

        FileInputStream fis = null;
        ObjectInputStream ois = null;

        try {

            fis = new FileInputStream(filePath);
            ois = new ObjectInputStream(fis);
            Object o = ois.readObject();

            SerialUser user = (SerialUser) o;
            System.out.println(user);
            System.out.println(user.toString());

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {

            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }

    }

    public static void main(String[] args) {

        Serial serial = new Serial();

        String filePath = "D:\\repository\\test.md";

        SerialUser user = new SerialUser(1, "KIM");

        // 파일에 객체 저장하기
        serial.saveObject(filePath, user);

        // 파일로부터 객체 가져오기
        serial.loadObject(filePath);

    }

}

 

 

② transient 예약어

 

  • transient 예약어를 사용하여 선언된 변수는 직렬화 대상에서 제외된다.
  • 비밀번호와 같이 보안성이 필요한 데이터에 사용한다.
transient private String password;

 

 

▷ 출처

https://devlog-wjdrbs96.tistory.com/268

728x90