Object Stream

Programming/Java 2013. 2. 18. 01:01

바이트, 문자, 데이터 타입에 더하여 Object 역시 스트림 처리가 가능합니다.
저장 대상이 되는 클래스에 인터페이스(Serializable)만 붙여주면 ObjectInputStream / ObjectOutputStream 사용이 가능합니다.

 

import java.io.*;

class SampleData implements Serializable
{
	public String str;
	public int id;
	public SampleData(String str, int id) {
		this.str = str;
		this.id = id;
	}
	public String getSampleData() {
		return id + "=" + str;
	}
}

public class ObjectStreamMain {
	public static void main(String[] args) throws IOException, ClassNotFoundException {

		SampleData s1 = new SampleData("이씨",101);
		SampleData s2 = new SampleData("김씨",102);

		// Serialization
		FileOutputStream fos = new FileOutputStream("test.txt");  
		ObjectOutputStream oos = new ObjectOutputStream(fos);  
		oos.writeObject(s1);
		oos.writeObject(s2);
		oos.close();

		System.out.println(s1 + ":" + s1.getSampleData());		//SampleData@618d26:101=이씨
		System.out.println(s2 + ":" + s2.getSampleData());		//SampleData@88e2dd:102=김씨

		// Deserialization
		FileInputStream fis = new FileInputStream("test.txt");  
		ObjectInputStream ois = new ObjectInputStream(fis);  
		SampleData sd1 = (SampleData)ois.readObject();
		SampleData sd2 = (SampleData)ois.readObject();
		ois.close(); 

		System.out.println(sd1 + ":" + sd1.getSampleData());	//SampleData@203c31:101=이씨
		System.out.println(sd2 + ":" + sd2.getSampleData());	//SampleData@4fc156:102=김씨
	}
}

WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,