쌍용교육(JAVA)/JAVA

쌍용교육 -JAVA 수업 16일차 실습 직렬화,역직렬

구 승 2024. 4. 12. 08:46

직렬화

package kr.s28.iostream;

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

//직렬화
/*
 * Serializable 인터페이스를 구현하면 해당 클래스는 객체 직렬화 대상이 되어
 * 언제든지 객체 직렬화를 수행할 수 있음.
 * Serializable 인터페이스가 구현되지 않으면 객체 직렬화 불가능
 */
class Customer implements Serializable{
	private String name;
	
	public Customer (String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "당신의 이름은 " + name ;
	}
}

public class SerialMain01 {
	public static void main(String[] args) {
		//직렬화할 객체 생성
		Customer c = new Customer("홍길동");
		
		System.out.println("===객체 직렬화 하기 ===");
		FileOutputStream fos = null;
		ObjectOutputStream oos = null; 
		try {
			//파일 생성
			fos = new FileOutputStream("object.ser");
			oos = new ObjectOutputStream(fos);
			//객체직렬화
			oos.writeObject(c);
			
			System.out.println("객체 직렬화가 완료되었습니다.");
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			//자원정리
			if(oos != null)try {oos.close();}catch(IOException e) {}; //늦게발생한걸 먼저 자원정리를 해줘야됨.
			if(fos != null)try {fos.close();}catch(IOException e) {};
		}
	}
}

===객체 직렬화 하기 ===
객체 직렬화가 완료되었습니다.

역직렬화

package kr.s28.iostream;

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

public class SerialMain02 {
	public static void main(String[] args) {
		System.out.println("===객체 역직렬화 하기===");
		FileInputStream fis = null;
		ObjectInputStream ois = null;

		try {
			fis = new FileInputStream("object.ser");
			ois = new ObjectInputStream(fis);
			
			//역직렬화 수행
			Customer m = (Customer)ois.readObject();//역직렬화 하는 함수 readObject
			System.out.println(m);

		}catch(FileNotFoundException e )
		{ e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}catch(ClassNotFoundException e ) {
			e.printStackTrace();
		}finally {
			if(ois != null)try {ois.close();}catch(IOException e ) {};
			if(fis != null)try {fis.close();}catch(IOException e ) {};
		}
	}
}

===객체 역직렬화 하기===
당신의 이름은 홍길동

직렬화

package kr.s28.iostream;

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

class UserInfo implements Serializable{
	private String name;
	private int age;
	private String address;
	
	public UserInfo(String name, int age, String address ) {
		this.name = name;
		this.age = age;
		this.address = address;
	}

	@Override
	public String toString() {
		return "이름 : " + name + "나이 : " + age + "주소 :"  + address ;
		//출력할 내용을 toString을 불러와서 보여줌. 
	}
}
public class SerialMain03 {
	public static void main(String[] args) {
		//직렬화할 객체 생성
		UserInfo u1 = new UserInfo("Jhon",20,"서울시");
		UserInfo u2 = new UserInfo("Sunny",18,"부산시");
		
		ArrayList<UserInfo> list = new ArrayList<UserInfo>();
		
		list.add(u1);
		list.add(u2);
		
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		
		try {
			//파일생성
			fos = new FileOutputStream("userInfo.ser");
			oos = new ObjectOutputStream(fos);
			//객체 직렬화 하기
			oos.writeObject(list);
			
			System.out.println("직렬화가 성공적으로 완료 되었습니다.");
			
		}catch(IOException e ) {
			e.printStackTrace();
		}finally {
			if(oos != null) try {oos.close();}catch(IOException e) {};
			if(fos != null) try {fos.close();}catch(IOException e) {};
		}
	}
}

직렬화가 성공적으로 완료 되었습니다.

역직렬화

package kr.s28.iostream;

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

public class SerialMain04 {
	public static void main(String[] args) {
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream("userInfo.ser");
			ois = new ObjectInputStream(fis);
			
			//역직렬화 작업
			ArrayList<UserInfo> list = (ArrayList<UserInfo>)ois.readObject();
			
			System.out.println(list);
			
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}finally {
			//자원정리
			if(ois != null) try {ois.close();}catch(IOException e) {};
			if(fis != null) try {fis.close();}catch(IOException e) {};
		}
	}
}

[이름 : Jhon나이 : 20주소 :서울시, 이름 : Sunny나이 : 18주소 :부산시]