본문 바로가기
BackEnd/Java

IO_ ObjectInputStream & ObjectOutputStream

by pplucy 2020. 11. 1.

* 보조스트림

 

 

* 직렬화(Serializable)

  : FileOutputStream/FileInputStream은 바이트기반이라 객체를 입력/출력하고자 하면 이 객체를

   바이트로 쪼개주는 작업을 해야하는데 이것이 바로 직렬화.

   (문자열을 바이트로 쪼개는 것은 String클래스의 getByte() 메소드)

 

1.  ObjectOutputStream

    : 객체를 바이트로 쪼개서 입력할 수 있게 도와주는 보조스트림

     - 파일에 쓸 객체들을 생성 -> try_with_resource구문 사용해서 객체들을 파일에 넣기

 

2. ObjectInputStream

   : 객체를 바이트로 쪼개서 출력할 수 있게 도와주는 보조스트림

    - While문 사용하여 객체 읽어오기 -> catch문으로 EOFException예외처리 해주기

 

 

* EOFException

  : 파일에서 모든 객체를 읽어내고 나면 발생하는 예외,

    이걸 catch문으로 잡아주지 않으면 객체를 다 읽어내서 나오는 문제를 정확히 파악하기 어렵다.

    단, EOFException이 IOException을 상속하기 때문에 catch문 맨 아래에 작성하게 되면

    IOExcepotion이 잡아먹어버린다. 꼭 catch문 맨 위에서 작성해줘야 한다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
import com.kh.filter.model.vo.Phone;
import com.kh.filter.model.vo.Student;
import com.kh.filter.model.vo.Teacher;
 
public class B_ObjectIO_2 {
    
    
    public void objectOutput() {
        
        
        // 파일에 쓸 객체 생성
        Phone phone = new Phone("애플"100);
        Student student = new Student("박미영"'F', phone);
        Teacher teacher = new Teacher("Pclass""하명도");
   
        //.dat : 데이터 파일을 의미하는 확장자
        //try_with_resource 구문 이용
        try(
             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.dat"))){
            
                    
            oos.writeObject(phone); //객체 넣기
            oos.writeObject(student);
            oos.writeObject(teacher);
            
            System.out.println("student.dat 파일 생성완료");
            
            
        } catch (FileNotFoundException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            
            e.printStackTrace();
        }
        
        
    }
        
        
        
        public void objectInput() { //객체 읽어오기
        
        try(
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.dat"))){
            
            //객체 읽어내기 
            while(true) {
                
                Object res = ois.readObject();
                System.out.println(res);
            }
        
            //EOFExecption: 파일에서 더이상 읽을게 없으면 발생하는 예외!
        } catch(EOFException e) {
            System.out.println("파일의 모든 객체를 출력하였습니다.");
            
            
        } catch (FileNotFoundException e) {
            
            e.printStackTrace();
            
        } catch (IOException e) {
            
            e.printStackTrace();
            
        } catch (ClassNotFoundException e) {
            
            e.printStackTrace();
        }
        
 
        
    }
    
 
        //기반스트림인 FileInputStream에 객체를 읽어오는 ObjectInputStream 과 속도향상을 위한 Buffer추가
        public void ObjectInputWithBuffer() {
            
            try(
                ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("student.dat")))) {
                    
                    
                    while(true) {
                        
                        Object res = ois.readObject();
                        System.out.println(res);
                    }
                    
                
                } catch (EOFException e) {
                
                System.out.println("파일의 모든 객체를 출력하였습니다.");
                    
                } catch (FileNotFoundException e) {
                    
                    e.printStackTrace();
                    
                } catch (IOException e) {
                    
                    e.printStackTrace();
                    
                } catch (ClassNotFoundException e) {
                
                    e.printStackTrace();
                }
            
        
        
    }    
        
        
    }

Colored by Color Scripter

cs

'BackEnd > Java' 카테고리의 다른 글

IO_OutputStreamWriter & InputStreamReader  (0) 2020.11.10
IO_FileWriter & FileReader  (0) 2020.11.10
IO_BufferedInputStream & BufferedOutputStream  (0) 2020.10.31
IO_FileOutPutStream & FileInputStream  (0) 2020.10.31
IO _ File 클래스  (0) 2020.10.31

댓글