반응형
Serialization & Deserialization
- 직렬화(serialization) : 객체를 스트림으로 만드는 작업
- 역직렬화(deserialization) : 스트림을 객체로 만드는 작업
객체를 스트림으로 만들면 좋은점 : 객체를 통채로 입력 및 출력 할 수 있다.
객체를 직렬화하고 역직렬화하는 프로그램
직렬화 가능 클래스란, java.io.Seiralizable 인터페이스를 구현하는 클래스
1. 직렬화 가능 클래스 선언
class Goods implements java.io.Serializable {
String name;
int num;
Goods(String name, int num) {
this.name = name;
this.num = num;
}
void addStock(int num) {
this.num += num;
}
int subtractStock(int num) throws Exception {
if (this.num < num)
throw new Exception("재고가 부족합니다.");
this.num -= num;
return num;
}
}
2. Goods 객체를 직렬화 하는 프로그램 - ObjectOutputStream
import java.io.*;
public class ObjectOutputStream1 {
public static void main(String args[]) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream("output.dat"));
// 객체를 직렬화
out.writeObject(new Goods("사과", 100));
out.writeObject(new Goods("복숭아", 50));
out.writeObject(new Goods("포도", 200));
}
catch (IOException ioe) {
System.out.println("파일로 출력할 수 없습니다.");
}
finally {
try {
out.close();
}
catch (Exception e) {
}
}
}
}
3. Goods 객체를 역직렬화하는 프로그램 - ObjectInputStream
import java.io.*;
public class ObjectInputStream1 {
public static void main(String args[]) {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("output.dat"));
while (true) {
Goods obj = (Goods) in.readObject();
System.out.println("물품명: " +obj.name + "\t상품수량: "+obj.num);
}
}
catch (FileNotFoundException fnfe) {
System.out.println("파일이 존재하지 않습니다.");
}
catch (EOFException eofe) {
System.out.println("");
}
catch (IOException ioe) {
System.out.println("파일을 읽을 수 없습니다.");
}
catch (ClassNotFoundException cnfe) {
System.out.println("해당 클래스가 존재하지 않습니다.");
}
finally {
try {
in.close();
}
catch (Exception e) {
}
}
}
}
반응형
'프로그래밍 언어 > Java' 카테고리의 다른 글
[Java] 멀티스레드 프로그래밍 - Thread 클래스 (0) | 2019.10.28 |
---|---|
[Java] GUI 프로그래밍 (0) | 2019.09.29 |
[Java] Java 라이브러리 탐색하기 / Java APIs (0) | 2019.09.18 |
[Java] LinkedList 클래스 / iterator 메소드 (0) | 2019.09.17 |
[Java] ArrayList 클래스 (0) | 2019.09.06 |