본문 바로가기

프로그래밍 언어/Java

[Java] 객체의 직렬화 serialization & 역직렬화 deserialization

반응형
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) {
			}
		}
	}
}

 

 

반응형