본문 바로가기
개발자 양성과정 필기노트/JAVA

자바 I/O - 객체 직렬화, 역직렬화

by jono 2021. 11. 14.

     I. 객체 직렬화 / ObjectOutputStream     


- 자바에서 사용하는 객체에 영속성을 부여하여 파일,네트워크로 내보내는 것.

- 직렬화 대상 클래스 정의시 Serializable 인터페이스 구현이 필수!!!

- transient -> 출력 대상에서 제외시킬 변수에 사용한다. => 출력시 null로 뜬다.

public class Ex01 {
    public static void main(String[] args) {	
        Person p = new Person("홍길동",20,"901010-1234567");//3.객체생성하여 데이터 초기화
        File f = new File("C:\\temporary\\serial_person.dat");//4. 파일경로&파일명 지정

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
            oos.writeObject(p);//5. 파일경로전달 받은 ObjectOutputStream객체생성, 메서드 호출하여 출력
        } catch (IOException e) {
        	e.printStackTrace();
        }
        System.out.println("객체 파일에 출력 완료");
    }
}

class Person implements Serializable{//1. 객체직렬화 대상 클래스를 정의, Serializable구현 필수!
	String name; int age;
	transient String jumin; //2.객체직렬화로 출력시 해당변수의 데이터는 null처리된다.
	
	public Person(String name, int age,String jumin) {
		super();
		this.name = name;
		this.jumin = jumin;
		this.age = age;
	}
	@Override
	public String toString() {
		return "[회원정보: 이름: "+name+", 나이: "+age+", 주민번호: "+jumin+"]";
	}
}

 


     II. 객체 역직렬화 / ObjectInputStream     


- 외부의 파일, 네트워크에서 데이터를 읽어들여 객체로 변환시키는 것.

1. FileInputStream객체를 생성하여 객체가 저장되어있는 파일의 경로와 파일명을 전달받음

2. ObjectInputStream객체를 생성하여 FileInputStream객체를 전달받음

3. ObjectInputStream객체의 readObject() 호출하여 객체데이터를 읽어들임

4. Object데이터형이므로 별도의 형변환이 필요하다

   -> 에러방지를 위해 하드코딩 노노 -> 타입체크할것!

5. 객체 역직렬화 완료!

Person p = new Person("홍길동",20,"901010-1234567");
File f = new File("C:\\temporary\\serial_person.txt");
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {	
	Object o = ois.readObject();//1. 객체가 저장된 파일에서 객체데이터를 읽어온다.
	if(o instanceof Person) {//2. 데이터가 Object형이므로 별도의 형변환 필요.
		Person pp = (Person)o; 
		System.out.println(pp.toString());
	}
} catch (ClassNotFoundException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}

댓글