public class ObjectStreamTest { private static String fileName = "D:\\person.obj";//매개변수 받은 객체를 파일로 출력 public static void writeobject(Object obj){ //인수로 받은 객체를 person.obj에 출력 //ObjectOutputStream 이용, 객체를 출력 - 객체 직렬화, 출력 대상 : instance 변수의 값들( attribute) ObjectOutputStream oos =null; try { //연결하면서 필터까지 추가한 내용 oos = new ObjectOutputStream(new FileOutputStream(fileName)); //쓰기작업시작-writeObject(object) oos.writeObject(obj); //매개변수로 받은 객체를 넘겨준다. } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(oos!=null) { try { oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static Object readObject(){ //person.obj파일에 젖아된 객체 정보를 읽어들여 다시 객체로 만든다. //ObjectInputStream - 객체를 입력받는 메소드 : 객체 역직렬화 //메소드 : readObject() : Objectream ObjectInputStream ois = null; Object obj = null; try { ois = new ObjectInputStream (new FileInputStream(fileName)); //읽기 obj = ois.readObject(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(ois!=null) { try { ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return obj; } public static void main(String[] args) { //PersonDTO p = new PersonDTO("id-111","112312","홍길동",123); //writeobject(p);//직렬화가 안되서 Exception오류가 나게 된다. Object obj = readObject(); PersonDTO dto = (PersonDTO)obj; System.out.println(dto); } }