Development Palette

직렬화 Serializtion 본문

Java

직렬화 Serializtion

징주 2021. 8. 22. 14:49

존재이유

  • 객체를 컴퓨터에 저장했다가 다음에 꺼내쓰거나, 네트워크를 통해 컴퓨터간에 서로 객체를 주고 받을 수 있다.

직렬화란?

  • 객체에 저장된 데이터를 스트림에 쓰기(write)위해 연속적인(serial) 데이터로 변환 하는 것을 의미
  • 역직렬화(deserializtion) : 반대로 스트림으로부터 데이터를 읽어서 객체를 만드는 것

왜 serial ??

  • 객체는 클레스에 정의된 인스턴스 변수의 집합이다. 따라서 객체를 저장한다는 것은 객체의 모든 인스턴스변수의 값을 저장한다는 것을 의미한다.
  • 어떤 객체를 저장(직렬화)하고자 한다면, 현재 객체의 모든 인스턴스 변수의 값을 저장한다.
  • 저장했던 객체를 다시 생성(역직렬화)하고자 한다면, 객체를 생성한 후에 객체를 저장했던 값을 읽어서 생성된 객체의 인스턴스변수에 저장한다.

ObjectInputStream, ObjectOutputStream 존재 이유

  • 클래스의 인스턴스 변수가 기본형일 때는 간단하지만,, 참조형 일 때는 어떻게??
  • 참조형은 주소값이 저장되어버린다... 그래서 값을 저장할 수 있게 변환해야함!!
  • 하지만 직접 구현하지 않아도 된다. 그 이유는 Serializble 인터페이스 
  • Serializble 인터페이스의 ObjectInputStream(역직렬화), ObjectOutputStream(직렬화)가 알아서 해줌~~

ObjectInputStream, ObjectOutputStream 사용법

예시) User타입의 객체를 직렬화 / 역직렬화

implements Serializble

  • 객체 타입의 클래스에 implements Serializble 붙여주기
public class User implements Serializable{ 
    String name; 
    int age; 
    double score; 

    public User(String name, int age, double score) {
        super(); 
        this.name = name; 
        this.age = age; 
        this.score = score; 
    }
}

직렬화 - ObjectOutputStream으로 변환 후 파일에 객체를 저장하기

User ob1=new User("민들레",20,89.5);

FileOutputStream fos = new FileOutputStream("extext.txt");
ObjectOutputSteam out = new ObjectOutputStream(fos);
out.writeObject(ob1); //저장할 객체

또는 아래처럼 줄여서 쓸 수 있다.

ObjectOutputSteam out = new ObjectOutputStream(new FileOutputStream("extext.txt"));
out.writeObject(ob1); //저장할 객체

역직렬화 - 파일 내용을 ObjectInputStream으로 변환 후 새로운 객체에 저장하고 데이터 읽어주기

FileInputStream fis = new FileInputStream("extext.txt");
ObjectInputStream in = new ObjectInputStream(fis);
User info = (User)in.readObject(); //User 타입의 info 객체를 생성하여 데이터를 저장

예시

직렬화 / 역직렬화 하기 위해 구현 명시

package com.testex.t0823_debug.serializeableex;

import java.io.Serializable;

//생성자 2개, +disp():void 추가
public class User implements Serializable{ // 객체 직렬화 구현 명시
    private String name;
    private int age;
    private double score;

//    public User() {
//        super();
//    }
    public User(String name, int age, double score) {
        //super();
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public void disp() {
        System.out.print("이름:"+name);
        System.out.print("  나이:"+age);
        System.out.println("  점수:"+score);
    }
}

직렬화

package com.testex.t0823_debug.serializeableex;

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

public class ObjectOutputMain {
    public static void main(String[] args) {
        User ob1=new User("민들레",20,89.5);
        User ob2=new User("개나리",22,73.5);

        //IO Stream(직렬화)
        try {
            ObjectOutputStream oos=
                        new ObjectOutputStream(new FileOutputStream("user.txt"));
            oos.writeObject(ob1);
            oos.writeObject(ob2);

            System.out.println("저장 되었습니다");
            oos.close();

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

역직렬화

package com.testex.t0823_debug.serializeableex;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectInputMain {
    public static void main(String[] args) {

        //IO Stream(역직렬화)
        try {
            ObjectInputStream oos=
                        new ObjectInputStream(new FileInputStream("user.txt"));
            User ob1=(User)oos.readObject();
            User ob2=(User)oos.readObject();

            ob1.disp();    //출력
            ob2.disp();

            oos.close();

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

'Java' 카테고리의 다른 글

HashMap 정렬  (0) 2021.09.29
싱글톤패턴(Singleton Pattern)  (0) 2021.08.23
Comparator / Comparable  (0) 2021.08.22
메모리  (0) 2021.08.08
변수  (0) 2021.08.05
Comments