JAVA
직렬화 (Serialization) 란?
diligentdev
2024. 3. 20. 22:21
728x90
Serialization이라는 것은 무엇일까요??
실제, Serializable 인터페이스를 보면 메소드가 하나도 없습니다. 그럼 이건 왜 있는 걸까요? 언제쓰는 걸까요?
public interface Serializable [
}
직렬화 목적
- Serialize는 우리가 만든 클래스가 파일에 읽거나 쓸 수 있도록 하거나,
- 다른 서버로 보내거나 받을 수 있게 합니다.
즉, Serialziable 인터페이스를 구현하면 JVM에서 우리가 만든 객체를 저장하거나 다른 서버로 전송할 수 있도록 해줌
직렬화란?
- 자바 시스템 내부에서 사용되는 객체 또는 데이터를 외부의 자바 시스템에서도 사용할 수 있도로 바이트(Byte)형태로 데이터 변환하는 기술
- 바이트로 변환된 데이터를 다시 객체로 변환하는 기술 를 아울러 말함
예제 코드
자바에서 ObjectOutputStream 클래스를 사용하면 객체를 저장할 수 있음
객체 저장 코드
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class ManageObject {
public static void main(String[] args) {
ManageObject manage = new ManageObject();
String fullPath = "/Users/choejeong-gyun/Documents/test.md";
//책 제목, 순서, 베스트셀러여부, 하루에 팔리는 양
SerialDTO dto = new SerialDTO("God of Java", 1, true, 100);
manage.saveObject(fullPath, dto);
}
public void saveObject(String fullPath, SerialDTO dto) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(fullPath);
oos = new ObjectOutputStream(fos);
oos.writeObject(dto);
System.out.println("Write Success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
FileOutputStream의 객체를 만든 후에 ObjectOutputStream의 매개변수로 넘겨줌
writeObject를 통 매개변수로 넘어온 객체를 저장
이렇게 객체를 해당 path에 저장하게 됨
객체를 읽을 때는 동일한 방식으로 FileInputStream과 ObjectInputStream 클래스를 사용
import java.io.*;
public class ManageObject {
public static void main(String[] args) {
ManageObject manage = new ManageObject();
String fullPath = "/Users/choejeong-gyun/Documents/test.md";
manage.loadObject(fullPath);
}
public void loadObject(String fullPath) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(fullPath);
ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
SerialDTO dto = (SerialDTO)obj;
System.out.println(dto);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
출력 결과
SerialDTO{booName='God of Java', bookOrder=1, bestSeller=true, soldPerDay=100}
728x90