. 객체단위의 입력과 출력도 마찬가지로 스트림을 기반으로한다. 한가지 주의할 점은 객체의 입/출력에서는 직렬화(Serializable) 라는 개념이 반드시 필요하다 직렬화라는것은 클래스의 구성을 파일이나 네트워크로 정상적으로 전달하기 위해 형태를 재구성하는 것이다 다시말해 일렬로 줄을 지어서 전송하여야 한다는것이다 자바큭에서는 이러한 번거로움을 해결하기 위하여 java.io.Serializable 이라는 인터페이스를 제공해 주었다.
. 직렬화 구현방법 전송하고자 하는 객체에 대해 Serializable 를 구현해주기만 하면 되는데 이 인터페이스 내부에는 재정의 할 메소드도 없다 클래스 선언부에서 [implements Serializable] 이라고만 적어주면 된다.
. 객체 출력
1 . 파일 출력용 File file = new File(“파일명”); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(….);
2 . 네트워크 출력용 Socket soc = new Socket(…..); BufferedOutputStream bos = new BufferedOutputStream(soc.getOutputStream()); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(….);
. 객체 입력
1 . 파일 입력용 File file = new File(“파일명”); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); ObjectInputStream ois = new ObjectInputStream(bis); try{ Object obj = ois.readObject(); }catch(ClassNotFoundException ee){}
2 . 네트워크 입력용 Socket soc = new Socket(); BufferedInputStream bis = new BufferedInputStream(soc.getInputStream()); ObjectInputStream ois = new ObjectInputStream(bis); try{ Object obj = ois.readObject(); }catch(ClassNotFoundException ee){}
classRound16_Ex12_SubimplementsSerializable{ // 출력 대상이 되는 클래스는 반드시 java,io.Serializable을 구현해야 한다 int x; int y; }
publicclassRound16_Ex12{ publicstaticvoidmain(String[] ar)throws IOException { Round16_Ex12_Sub ap = new Round16_Ex12_Sub(); ap.x = 100; ap.y = 200; // 출력 대상 객체를 생성하고 x와 y의 값을 적절하게 변경한다 File dir = new File("C:\\java\\work"); File file = new File(dir, "object.txt"); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(bos); // 출력 대상에 대한 Stream객체를 ObjectOutputStream으로 생성한다. oos.writeObject(ap); // ap라는 객체를 파일로 전송한다. } }
publicclassRound16_Ex13{ publicstaticvoidmain(String[] ar)throws IOException { File dir = new File("c:\\java\\work"); File file = new File(dir, "object.txt"); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); ObjectInputStream ois = new ObjectInputStream(bis); // 위의 예제에서 생성한 Object.txt.파일에 대한 입력 Stream을 ObjectInputStream // 의 객체형태로 생성한다. Object obj = null; try { obj = ois.readObject(); // 저장되어 있는 객체를 Object 형태로 입력밭는다. 이때 해당 클래스를 찾을수 없을 경우 // 예외를 처리해 주어야 한다. } catch (ClassNotFoundException ee) { } ois.close(); // 불러온 객체를 Object type으로 담은후 InputStream을 닫는다. Round16_Ex12_Sub ap = (Round16_Ex12_Sub) obj; // 전달된Object의 원래 형태가 Round16_Ex12_sub 이므로 강제 형변환을 해준다 . System.out.println("x = " + ap.x); System.out.println("y = " + ap.y); } }