목차
출처
https://steady-coding.tistory.com/576
https://hub1234.tistory.com/26
https://velog.io/@wansook0316/Serialization-Deserialization
https://flowarc.tistory.com/entry/Java-객체-직렬화Serialization-와-역직렬화Deserialization
데이터 직렬화와 역직렬화
- 데이터 직렬화
- 메모리를 디스크에 저장하거나, 네트워크 통신에 사용하기 위한 형식으로 변환하는 것
- 데이터 역직렬화
- 디스크에 저장한 데이터를 읽거나, 네트워크 통신으로 받은 데이터를 메모리에 쓸 수 있도록 변환하는 것
직렬화가 필요한 이유
값 형식 데이터
- 스택에 메모리가 쌓이고, 값으로 직접 접근이 가능함: int, float, char
참조 형식 데이터
- 객체를 선언하면 힙에 메모리가 할당되고, 스택에서 이 메모리를 참조함. 값을 직접 접근 X: 대부분의 객체(String, Class)
값 형식 데이터는 디스크에 저장하거나 통신할 때 사용할 수 있지만, 참조 형식 데이터는 프로그램 실행/종료마다 새로운 메모리에 할당되기 때문에 그 값에 접근할 수 없다.
직렬화
직렬화: 각 주소 값이 가지는 데이터를 전부 끌어 모아서 값 형식 데이터로 변환 (Text / Binary)
이러한 데이터는 디스크에 저장하거나 통신할 때 파싱할 수 있는 유의미한 데이터가 됨
직렬화의 종류
csv, json, xml | binary | |
장점 | - 사람이 읽을 수 있는 형태 - 최근 많이 사용 |
- 저장 공간 효율적으로 사용 가능 - 파싱 시간 빠름: 데이터 양 많을 때 사용) - i.e: Protocol Buffer, Apache Avro |
단점 | - 파싱 시간 오래 걸림(데이터 적을때 사용) - 저장 공간 효율성 떨어짐 |
- 사람이 읽을 수 없음 |
- Java 직렬화
Java 시스템 간의 데이터 교환이 필요할 때 사용
Java의 직렬화(Serialization)
객체를 직렬화하여 전송 가능한 형태로 만드는 것
객체들의 데이터를 연속적인 데이터로 변형하여 Stream을 통해 데이터를 읽도록 해줌
JVM의 메모리에 상주(힙 또는 스택)되어 있는 객체 데이터를 바이트 형태로 변환하는 기술.
주로 객체들을 통째로 파일로 저장하거나 전송하고 싶을 때 주로 사용
역직렬화(Deserialization)
직렬화된 파일 등을 역으로 직렬화하여 다시 객체의 형태로 만드는 것
저장된 파일을 읽거나 전송된 스트림 데이터를 읽어 원래 객체의 형태로 복원
직렬화된 바이트 형태의 데이터를 객체로 변환해서 JVM으로 상주시키는 기술
자바 직렬화 방법
Serializable 인터페이스를 구현해야 함 (java.io.Serializable)
직렬화에서 제외하고 싶은 변수는 transient 선언
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.dat"))) {
oos.writeObject(this.list);
} catch (Exception e) {
e.printStackTrace();
}
if (file.exists()) {
// try with resources
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
this.list = (List<User>) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}
직렬화: 자바에 있는 데이터를 바이트 형태로 변환하여 저장: ObjectOutputStream 사용
역직렬화: 외부의 데이터를 객체로 변환: ObjectInputStream 사용
serialVersionUID
클래스의 변경 여부를 확인하기 위한 키
직렬화할 때의 UID와 역직렬화 할 때의 UID가 다를 경우 예외 발생 (InvalidClassException)
- 클래스 내용이 수정
- 컴파일러가 다를 경우
직렬화되는 객체에 UID가 설정되지 않았을 경우 컴파일러가 자동 생성 (설정하는 것을 권장)
private static final long serialVersionUID = 1L;
'Java' 카테고리의 다른 글
[백준] 10986 - 나머지 합 (자바/Java) (0) | 2022.09.27 |
---|---|
[자바/Java] 예외 처리 (Exception) (0) | 2022.07.28 |
[자바/Java] 객체 참조 시 인터페이스 사용 이유 (0) | 2022.07.28 |
[자바/Java] 제네릭 Generics (0) | 2022.07.27 |
[자바/Java] 클래스 다형성(Polymorphism) (0) | 2022.07.25 |