ObjectInput/OutputStream: 객체를 입출력하는 스트림클래스
- Serializable 인터페이스: 메소드 없음. 상속(implements)받은 객체들은 입출력이 가능하다는 것을 표시만 해주는 것.
- Object의 자손 String클래스는 Serializable을 상속받았는데, 그래서 ObjectIn/OutputStream은 Serializable을 상속받은 메소드만 입출력할 수 있음
-주요 메소드
리턴타입이 오브젝트니까 읽어오는 메소드는 ~Object()가 된다.
writeObject(): 인자에 출력할 객체를 생성해야 함. 예 writeObject(new String("안녕"))
readObject()
- 예시
try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.ser")); oos.writeObject(new String("hello")); oos.writeObject(new Date()); //또는 객체 생성한 뒤 출력할 수 있음 Person p = new Person(); ois.writeObject(p); // oos.close(); System.out.println("파일로 객체 저장 완료!"); } catch(IOException ie) { System.out.println(ie.getMessage()); } // // try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser")); Object str = ois.readObject(); Object date = ois.readObject(); System.out.println(str); System.out.println(date); //만든 클래스 객체 불러오기 //Object는 자손의 메소드를 사용할 수 없기 때문에 형변환을 해주어야 사용이 가능해짐 Object o = ois.readObject(); Person p = (Person)o; //한 줄로 쓰면 이렇게 됨 Person o = (Person)ois.readObject(); System.out.println(o.메소드()); ois.close(); } catch(IOException ie) { System.out.println(ie.getMessage()); }catch(ClassNotFoundException ce) { System.out.println(ce.getMessage()); }