ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 직렬화,역직렬화-22.04.01
    고급자바 2022. 4. 1. 17:24
    728x90

    객체 입출력 보조 스트림 예제(직렬화와 역직렬화)

    transient => 직렬화가 되지 않을 멤버변수에 지정한다.
       (* static 필드도 직렬화가 되지 않는다.)
       직렬화가 되지 않는 멤버변수는 기본값으로 저장된다.
       (참조형 변수: null, 숫자형 변수:0)

    public class T15_ObjectStreamTest {
    
    	public static void main(String[] args) {
    		// Member 인스턴스 생성
    		Member mem1=new Member("홍길동", 20, "대전");
    		Member mem2=new Member("일지매", 30, "경기");
    		Member mem3=new Member("이몽룡", 40, "강원");
    		Member mem4=new Member("성춘향", 20, "광주");
    		
    		ObjectOutputStream oos=null;
    		
    		try {
    			//객체를 파일에 저장하기
    			
    			//출력용 스트림 객체 생성
    			oos=new ObjectOutputStream(new FileOutputStream("d:/D_Other/memObj.bin"));
    			
    			//쓰기 작업
    			oos.writeObject(mem1); //직렬화
    			oos.writeObject(mem2); //직렬화
    			oos.writeObject(mem3); //직렬화
    			oos.writeObject(mem4); //직렬화
    			
    			System.out.println("쓰기 작업 완료...");
    			
    		}catch(IOException ex) {
    	         ex.printStackTrace();
    	      }finally {
    	         try {
    	            oos.close();
    	         } catch (IOException e) {
    	            e.printStackTrace();
    	         }
    	      }
    	}
    
    }

    <MemberVO만들기>

    transient => 직렬화가 되지 않을 멤버변수에 지정한다.
       (* static 필드도 직렬화가 되지 않는다.)
       직렬화가 되지 않는 멤버변수는 기본값으로 저장된다.
       (참조형 변수: null, 숫자형 변수:0)

    더보기

    transient

    직렬화 않시키고싶을 상황: 민감한 정보(비번,주민번호), 불필요한 정보에 붙인다.

    private String name;
    	private transient int age;
    	private String addr;

    바꿔보면 

    class Member implements Serializable{  //자바는 Serializable인터페이스를 구현한 클래스만 직렬화 할 수 있도록 제한하고 있음.
    	
    	/*
    	  transient => 직렬화가 되지 않을 멤버변수에 지정한다.
    	  			(* static 필드도 직렬화가 되지 않는다.)
    	  		직렬화가 되지 않는 멤버변수는 기본값으로 저장된다.
    	  		(참조형 변수: null, 숫자형 변수:0)
    	 */
    	private String name;
    	private int age;
    	private String addr;
    	
    	public Member(String name, int age, String addr) {
    		super();
    		this.name = name;
    		this.age = age;
    		this.addr = addr;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    
    	public String getAddr() {
    		return addr;
    	}
    
    	public void setAddr(String addr) {
    		this.addr = addr;
    	}
    	
    	
    	
    }
    더보기

    자바는 Serializable인터페이스를 구현한 클래스만 직렬화 할 수 있도록 제한하고 있음.

    class Member implements Serializable

    Serializable는 추상메서드가 없다. 표식인터페이스 

    Member는 이제 Serializable 타입이됨.

    그래서 Serializable mem4=new Member("성춘향", 20, "광주"); 가능

     

    <저장한 객체를 읽어와 출력하기>

    ObjectInputStream ois=null;
    		
    		try {
    			
    			//객체를 읽기위한 스트림 객체 생성
    			ois=new ObjectInputStream(new FileInputStream("d:/D_Other/memObj.bin"));
    			
    			
    			Object obj =null;
    			
    			while((obj=ois.readObject())!=null) {
    				// 읽어온 데이터를 원래의 객체형으로 변환 후 사용한다.
    				Member mem=(Member)obj;
    				System.out.println("이름: "+mem.getName());
    				System.out.println("나이: "+mem.getAge());
    				System.out.println("주소: "+mem.getAddr());
    				System.out.println("-------------------------");
    			}
    			
    			
    		}catch(IOException ex) {
    	         ex.printStackTrace();
    	      }catch(ClassNotFoundException ex){
    	    	ex.printStackTrace(); 
    	      } finally {
    	         try {
    	            ois.close();
    	         } catch (IOException e) {
    	            e.printStackTrace();
    	         }
    	      }

    ->파일을 읽다가 파일 맨끝에 읽어올게 없어서 예외 발생 (항상날 수 밖에...)

    그래서 좀 수정...

    }catch(IOException ex) {
    	        // ex.printStackTrace();
    			//더 이상 읽어올 객체가 존재하지 않을 때 예외 발생함.
    			System.out.println("출력 작업 끝...");
    	      }catch(ClassNotFoundException ex){
    	    	ex.printStackTrace(); 
    	      } finally {
    	         try {
    	            ois.close();
    	         } catch (IOException e) {
    	            e.printStackTrace();
    	         }
    	      }

    +기능 더 추가

    <객체 파일에 저장하기>

    //출력용 스트림 객체 생성
    			//기반스트림을감싸주면 된다.
    			oos=new ObjectOutputStream(
    					new BufferedOutputStream(
    					new FileOutputStream("d:/D_Other/memObj.bin")));

    <저장한 객체 읽어올때>

    //객체를 읽기위한 스트림 객체 생성
    			ois=new ObjectInputStream(
    					new BufferedInputStream(
    					new FileInputStream("d:/D_Other/memObj.bin")));

    =>결과 동일~

    728x90
Designed by Tistory.