본문 바로가기

JAVA

java.io 패키지 - 객체 직렬화 실습

클래스 파일


import java.io.Serializable;

 

public class Person implements Serializable {

        private String name;

        private int age;

        private String email;

       

        public Person(String name, int age, String email){

               super();

               this.name = name;

               this.age = age;

               this.email = email;

        }

        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 String getEmail() {

               return email;

        }

        public void setEmail(String email) {

               this.email = email;

        }

}


 

 

 

 

파일 생성


import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

//객체 직렬화 실습

//ObjectOutputStream

 

public class FileIoEx01 {

 

        public static void main(String[] args) {

               ObjectOutputStream oos = null;

              

               try {

                       oos = new ObjectOutputStream(new FileOutputStream("c:\\dirs\\serial.dat"));

                       Person p = new Person("홍길동", 27, "test@test.com");

                       oos.writeObject(p);

               } catch (FileNotFoundException e) {

               } catch (IOException e) {

               } finally{

                       if(oos != null) try{oos.close();} catch(IOException e){}

               }

              

        }

 

}


 

 

 

 

 

파일 읽기(불러오기)


import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.ObjectInputStream;

//객체 직렬화 실습 : 한글이나 워드 같은 외부 파일을 불러옴 (하나의 객체로 보고 불러옴)

//ObjectInputStream

 

public class FileIoEx02 {

 

        public static void main(String[] args) {

               ObjectInputStream ois = null;

              

               Person p;

               try {

                       ois = new ObjectInputStream(new FileInputStream("c:\\dirs\\serial.dat"));

                       p = (Person)ois.readObject();

                       System.out.println(p.getName());

                       System.out.println(p.getAge());

                       System.out.println(p.getEmail());

               } catch (FileNotFoundException e) {

 

               } catch (ClassNotFoundException e) {

 

               } catch (IOException e) {

 

               } finally {

                       if(ois != null) try{ois.close();} catch (IOException e){}

               }

                      

        }

}