본문 바로가기
JAVA SE/Code

CODE[20.07.31/Day_17] Java SE / IO(Object Serialization 객체 직렬화)

by 파프리카_ 2020. 7. 31.
728x90
반응형

[ IO ]

객체 직렬화 ( Object Serialization )

java.io.Serializable


객체 직렬화 / 역직렬화 List 예제

 

main class

 

1. output 예제  : 객체 직렬화 object → file

/TestObjectOutputList.java

package step2;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import model.Product;

public class TestObjectOutputList {
	public static void main(String[] args) {
		ArrayList<Product> list = new ArrayList<Product>();
		list.add(new Product("a", "컵케익", "파리바게트"));
		list.add(new Product("b", "초코빵", "뚜레쥬르"));
		list.add(new Product("c", "식빵", "아띠블랑제"));

		String savePath = "C:\\kosta203\\iotest\\productList.obj";

		try 
		{
			// 1. 경로(savePath)에 있는 파일 읽기(연결) & productList 파일 생성
			// FileOutputStream 이용
			FileOutputStream fos = new FileOutputStream(savePath);
			
			// 2. productList 객체를 직렬화하여 제공
			/* --> 객체 직렬화를 위해 Product 클래스에
			 *  Serializable interface를 implements 해주어야 한다.
			 */
			// ObjectOutputStream 이용
			ObjectOutputStream oos = new ObjectOutputStream(fos);

			// 3. productList 정보를 productList 파일에 입력
			// writeObject 이용
			oos.writeObject(list);

			// 4. exception 없을 시 출력
			System.out.println("객체 직렬화하여 productList.obj에 list 저장 완료");

			// 5. output object 닫기
			oos.close();
		}

		catch (FileNotFoundException e) 
		{
			e.printStackTrace();

		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}

	}
}

 

2. input 예제 : 객체 역직렬화 file → object

/TestObjectInputList.java

package step2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import model.Product;

public class TestObjectInputList {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		String savePath = "C:\\kosta203\\iotest\\productList.obj";
		ArrayList<Product> list = new ArrayList<Product>();
		
		try
		{
			// 1. 경로(savePath)에 있는 파일 가져오기(연결)
			// FileInputStream 이용
			FileInputStream fis = new FileInputStream(savePath);
			
			// 2. input object stream(object) 객체 생성
			// ObjectInputStream 이용
			ObjectInputStream ois = new ObjectInputStream(fis);
			
			// 3. input object(ois)에 담긴 정보를 list에 담기
			// : ois는 Object type으로 반환된다
			// 타입을 Object -> ArrayList<Product>로 downcasting 필요
			// readObject() 이용
			list = (ArrayList<Product>)ois.readObject();
			
			// 4. 정보 하나씩 출력
			for (int i = 0; i < list.size(); i++) {
				System.out.println(list.get(i));
			}
			
			// 5. input object 닫기
			ois.close();
		}
		
		catch (FileNotFoundException fe)
		{
			fe.printStackTrace();
		}
		
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		catch (ClassNotFoundException ce) {
			ce.printStackTrace();
		}
		
	}
}

 

 

VO class

 

/Product.java

package model;

import java.io.Serializable;

public class Product implements Serializable{

	private static final long serialVersionUID = 8440559517099448018L;
	private String id;
	private String name;
	private String maker;
	
	@Override
	public String toString() {
		return "Product [id=" + id + ", name=" + name + ", maker=" + maker + "]";
	}

	public Product(String id, String name, String maker) {
		super();
		this.id = id;
		this.name = name;
		this.maker = maker;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getMaker() {
		return maker;
	}

	public void setMaker(String maker) {
		this.maker = maker;
	}
	
	
}

 

728x90
반응형