Archives
Recent Posts
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Today
Total
관리 메뉴

안드로이드 개발자의 창고

[Java 9일차] ObjectStream 본문

Computer/Java

[Java 9일차] ObjectStream

Wise-99 2023. 5. 9. 20:30

 

 

출처 : 안드로이드 앱스쿨 2기 윤재성 강사님 수업 PPT

 

 

 

📖 ObjectStream이란?

  • 메모리상에 존재하는 객체를 송수신 할 수 있는 필터 스트림이다.
  • 필터 스트림이므로 기본 스트림이 필요하다.
  • 자바 프로그램 간에만 가능하다.

 

📖 직렬화란?

  • 메모리 상에 존재하는(메모리에 나눠져 관리되고 있는) 객체를 출력할 수 있는 형태(바이트 배열 형태)로 만드는 것을 가르켜 직렬화 라고 부른다.
  • 직렬화 하지 않은 객체를 스트림을 통해 입출력할 수 없다.
  • 자바에서는 직렬화하기 위해 Serializable 이라는 인터페이스를 구현하면 된다.

 

📖 예제 전체 코드

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class MainClass {
	public static void main(String[] args) {
		
		saveObject();
		loadObject();
	}
	
	public static void saveObject() {
		try {
            // 기본 스트림
			FileOutputStream fos = new FileOutputStream("test100.dat");
			
			// 객체 출력 스트림
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            
            // 저장할 객체
            TestClass t1 = new TestClass(100, 200);
            TestClass t2 = new TestClass(300, 400);
            
            // 객체를 쓴다.
            oos.writeObject(t1);
            oos.writeObject(t2); 
            
            oos.flush();
            oos.close();
            fos.close();
            
            System.out.println("객체 쓰기 완료");
            
        }catch(Exception e) {
            e.printStackTrace();
        }
	}
	
	public static void loadObject() {
        try {
        	// 기본 스트림 생성
        	FileInputStream fis = new FileInputStream("test100.dat");
        	
        	// 객체 읽기 스트림
            ObjectInputStream ois = new ObjectInputStream(fis);
            
            // 객체를 복원한다.
            TestClass t10 = (TestClass)ois.readObject();
            TestClass t20 = (TestClass)ois.readObject();
        	
            ois.close();
            fis.close();
            
            t10.printData(); // memberA : 100, memberB : 200
            t20.printData(); // memberA : 300, memberB : 400
            
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

// 객체 직렬화를 위해 Serializable 인터페이스를 구현한다.
class TestClass implements Serializable {
	int memberA;
	int memberB;
	
	public TestClass(int memberA, int memberB) {
		this.memberA = memberA;
		this.memberB = memberB;
	}
	
	public void printData() {
        System.out.printf("memberA : %d\n", memberA);
        System.out.printf("memberB : %d\n", memberB);
    }
}

 

 

✔️ 코드 해석

public static void saveObject() {
		try {
			FileOutputStream fos = new FileOutputStream("test100.dat");

            ObjectOutputStream oos = new ObjectOutputStream(fos);
            
            // 저장할 객체
            TestClass t1 = new TestClass(100, 200);
            TestClass t2 = new TestClass(300, 400);
            
            // 객체를 쓴다.
            oos.writeObject(t1);
            oos.writeObject(t2); 
            
            oos.flush();
            oos.close();
            fos.close();
            
            System.out.println("객체 쓰기 완료");
            
        }catch(Exception e) {
            e.printStackTrace();
        }
	}
  • FileOutputStream fos를 선언하여 "test100.dat"이라는 파일을 만든다.
  • 객체를 파일에 저장하기 위해 ObjectOutputStream oos를 선언한다.
  • 선언한 객체 t1과 t2를 writeObject() 를 통해 저장한다.

 

 

 

public static void loadObject() {
        try {
        	FileInputStream fis = new FileInputStream("test100.dat");
        	
            ObjectInputStream ois = new ObjectInputStream(fis);
            
            TestClass t10 = (TestClass)ois.readObject();
            TestClass t20 = (TestClass)ois.readObject();
        	
            ois.close();
            fis.close();
            
            t10.printData();
            t20.printData();
            
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}
  • FileInputStream fis를 선언하여 "test100.dat"이라는 파일을 읽어온다.
  • 저장한 객체를 불러오기 위해 ObjectInputStream ois를 선언한다.
  • ois.readObject()를 이용하여 객체를 읽어온다.
    • 이 때 읽어온 객체의 타입은 Object이기 때문에 TestClass의 객체인 t10에 저장하지 못한다.
    • 따라서 (TestClass)로 형변환을 하여 저장한다.
  • t1과 t2를 통해 printData()를 불러온다.

 

 

 

class TestClass implements Serializable {
	int memberA;
	int memberB;
	
	public TestClass(int memberA, int memberB) {
		this.memberA = memberA;
		this.memberB = memberB;
	}
	
	public void printData() {
        System.out.printf("memberA : %d\n", memberA);
        System.out.printf("memberB : %d\n", memberB);
    }
  • 객체 직렬화를 위해 Serializable 인터페이스를 구현한다.
  • 객체를 송수신하기 위해서는 반드시 객체 직렬화를 해줘야 한다.

'Computer > Java' 카테고리의 다른 글

[10일차 Java] Network  (0) 2023.05.10
[9일차 Java] 2ByteStream  (0) 2023.05.09
[9일차 Java] DataStream  (0) 2023.05.09
[9일차 Java] FileStream  (0) 2023.05.08
[8일차 Java] Collection / List / Map / Set  (0) 2023.05.07