개인참고자료/자바(네트워크)

객체 스트림 - 윈도우 저장과 읽기

경진 2008. 7. 17. 08:16
윈도우 저장과 읽기

객체 직렬화가 불가능한 객체는 전송되지 않는다.

1. 윈도우 객체인 HelloWindow.java를 작성한다.
2. 객체 직렬화 기술을 이용해서 HelloWindow를 파일로 저장할 WindowObjectOutputStreamTest.java를 작성한다.
3. 파일에 저장된 윈도우 객체를 읽어 들일 WindowObjectInputStreamTest.java를 작성한다.

윈도우 객체를 만든 후 저장하고 읽어오는 예제다.

import java.io.Serializable;
import java.awt.event.*;
import java.awt.*;

public class HelloWindow extends Frame implements Serializable{
   
    public HelloWindow(){
        super("Hello Window");
        setLayout(new BorderLayout());
        add("Center", new Label("Hello Window"));
        addWindowListener(new WindowEventHandler());
        setSize(200, 200);
    }

    class WindowEventHandler extends WindowAdapter{
        public void windowClosing(WindowEvent e) {
            System.out.println("윈도우를 종료합니다.");
            System.exit(0);
        }
    }
}

"Hellow Window"라는 레이블을 출력하는 윈도우 객체다. 마샬링될 수 있도록 java.io.Serializable 인터페이스를 구현하고 있다.

        addWindowListener(new WindowEventHandler());

HelloWindow의 내부 클래스인 WindowEventHandler 객체를 윈도우 리스너에 등록시킨다.
윈도우의 x 버튼을 클릭할 경우 "윈도우를 종료합니다" 라는 메시지를 출력하고 종료한다.

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

public class WindowObjectOutputStreamTest {
    public static void main(String[] args) {
        FileOutputStream fout = null;
        ObjectOutputStream oos = null;

        HelloWindow hwin = new HelloWindow();
       
        try{
            fout = new FileOutputStream("hwin.dat");
            oos = new ObjectOutputStream(fout);
           
            oos.writeObject(hwin);
           
            System.out.println("저장되었습니다.");
            hwin.setVisible(true);
        }catch(Exception ex){
        }finally{
            try{
                oos.close();
                fout.close();
            }catch(IOException ioe){}
        } // finally
    } // main end
}

WindowObjectOutputStreamTest.java는 HellowWindow 객체를 생성한 후 마샬링해서 hwin.dat 파일에 저장하게 된다. 저장한 후 Frame에 있는 setVisible() 메소드를 호출해서 화면에 윈도우가 보여지게 한다.

실행된 상태에서 x 버튼을 클릭하면 "저장되었습니다. 윈도우를 종료합니다."라는 메시지를 출력한 후 프로그램은 종료한다.

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

public class WindowObjectInputStreamTest {

    public static void main(String[] args) {
        FileInputStream fin = null;
        ObjectInputStream ois = null;

        try{
            fin = new FileInputStream("hwin.dat");
            ois = new ObjectInputStream(fin);
           
            HelloWindow hwin = (HelloWindow)ois.readObject();
            hwin.setVisible(true);
        }catch(Exception ex){
        }finally{
            try{
                ois.close();
                fin.close();
            }catch(IOException ioe){}
        } // finally
    } // main end
}

WindowObjectInputStreamTest.java는 hwin.dat 파일에 마샬링되어 저장된 우니도우 객체를 읽어 들이는 예제다. 읽어들인 윈도우는 setVisible() 메소드를이용해서 화면에 보여지게 할 수 있다.

결과는 윈도우 창은 보이나 x 버튼을 클릭해도 윈도우가 종료되지 않는다. 그 이유는 HelloWindow 클래스 내부 클래스인 WindowEventHandler 객체가 java.io.Serializable 인터페이스를 구현하지 않고 있기 때문이다.

객체일 경우, java.io.Serializable 인터페이스를 구현하지 않으면 마샬링되지 않는다는 것을 반드시 기억해야 한다. 이 문제를 해결하려면 HelloWindow의 WindowEventHandler 객체의 선언 부분을 아래와 같이 수정해야 한다.

수정 전 : class WindowEventHandler extends WindowAdapter{
수정 후 : class WindowEventHandler extends WindowAdapter implements Serializable{

수정했다면 다시 컴파일하고 실행한다. 이제 읽어 들인쪽에서도 x 버튼을 클릭할 경우 윈도우가 종료된다.