ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] 객체를 직렬화 하여 파일에 쓰고 읽기
    JAVA 2012. 2. 8. 22:45

    1. 직렬화

    FileOutputStream fileStream = new FileOutputStream("MyGame.ser"); // 파일에 쓰는 역할
    ObjectOutputStream os = new ObjectOutputStream(fileStream); // 파일에 쓰기전에 직렬화 하는 역할
    // 두개의 스트림을 연결함, 연쇄(chain)이라고 함
    // ObjectOutputStream은 객체를 직렬화하여 저장하는 역할을 하고
    // FileOutputStream은 그걸 받아서 파일로 저장하는 역할을 한다.

    TheThings objectOne;

    os.writeObject(objectOne); // 위 두개 스트림을 타고 직렬화->파일출력 수행
    os.writeObject(objectTwo);
    os.writeObject(objectThree);
    // 이때 objectOne 객체는 Serializable 을 implements한 클래스의 객체여야 함 (조상중에 그러한 클랙스가 있다면 안해도됨)
      
    os.close();

    >> 객체 안에서 또다른 객체를 참조하고 또 그안에서 또다른 객체를 참조할때 직렬화는 어떻게 되나?
    --> 객체가 직렬화 되면 그 안에 참조되는 객체들도 자동으로 직렬화된다.

    >> Serializable 을 implements 한 클래스 내에서 직렬화 할 수 없는 객체가 있을때
    --> 앞에 transient 예약어를 붙여주면 직렬화 하지 않고 건너뛴다
          ex) transient String dontSerial;



    2. 역질렬화
    : 객체복구

    FileInputStream fileStream = new FileInputStream("MyGame.ser"); // 직렬화해서 썼던 파일을 다시 읽오는 역할
    ObjectInputStream is = new ObjectInputStream(fileStream); // 읽어온 직렬화된 내용을 역직렬화 하는 역할

    Object one = is.readObject();
    Object two = is.readObject();
    Object three = is.readObject();
    // 썼던 순서대로 읽어 올 수 있음

    TheThings thingOne = (TheThings) one; //읽어온 것을 원래 객체형태로 캐스팅
    TheThings thingTwo = (TheThings) two;
    TheThings thingThree = (TheThings) three;

    is.close();


    기억하시길.....
    1. 객체를 직렬화하여 파일에 저장할때는 FileOutputStreamObjectOutputStream 의 연쇄
    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("MyGame.ser"));

    객체를 직렬화 하여 파일로 부터 읽을때는 FileInputStream 과 ObjectInputStream 의 연쇄
    ObjectInputStream is = new ObjectInputStream(new FileInputStream("MyGame.ser"))

    주고받고읽고쓸때...객체랑 텍스트파일이랑 방법이 좀 다름!


Designed by Tistory.