잡동사니에도 사랑을

[21.08.25] ObjectWriteMain, ObjectReadMain, PersonDTO 본문

JAVA_SE/11_io

[21.08.25] ObjectWriteMain, ObjectReadMain, PersonDTO

luvforjunk 2021. 8. 29. 21:22
728x90
반응형

////////PersonDTO

 

package io;

 

import java.io.Serializable;

 

public class PersonDTO implements Serializable {

         // Serializable interface인데 추상메소드가 1 없다

         // 그래서 한번만 써주면 된다

         private String name;

         private int age;

         private double height;

 

// private이라 외부에서 접근을 못하니 setter, getter 잡아주기

         public String getName() {

                  return name;

         }

 

         public void setName(String name) {

                  this.name = name;

         }

 

         public int getAge() {

                  return age;

         }

 

         public void setAge(int age) {

                  this.age = age;

         }

 

         public double getHeight() {

                  return height;

         }

 

         public void setHeight(double height) {

                  this.height = height;

         }

}

 

// Serializable 항목들을 묶어준 형태로 갖고 있는

//Serializable 넣어주면 된당

 

////////ObjectWriteMain

 

package io;

 

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

 

public class ObjectWriteMain {

 

         public static void main(String[] args) throws IOException {

                  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("result2.txt"));

                  // 하나씩 보내지 않고 객체 생성

                  PersonDTO dto = new PersonDTO();

                  dto.setName("홍길동");

                  dto.setAge(25);

                  dto.setHeight(185.3);

 

                  oos.writeObject(dto); // dataStream 달리 write 한번 들어감

                  oos.close();

         }

}

 

// PersonDTO serializable 걸려 있지 않다고 NotSerializableException 오류가

// 홍길동은 String타입으로 객체인데

// String class 자체적으로 Serializable Comparable<String> 갖고 있다

// 문자열은 이름은 그냥 간거

 

////////ObjectReadMain

 

package io;

 

import java.io.FileInputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

 

public class ObjectReadMain {

 

         public static void main(String[] args) throws IOException, ClassNotFoundException {

                  ObjectInputStream ois = new ObjectInputStream(new FileInputStream("result2.txt"));

 

                  PersonDTO dto = (PersonDTO) ois.readObject();

                  // 자식 = (자식)부모. DTO 담겨 있는데 꺼내오는 Object 꺼내오자고 하니

                  // Casting 안걸어줘서 에러가 뜨는데,

 

                  System.out.println("이름 = " + dto.getName());

                  System.out.println("나이 = " + dto.getAge());

                  System.out.println(" = " + dto.getHeight());

                  ois.close();

         }

}

728x90
반응형