Java - Scanner,InputStream,BufferedReader

2020. 7. 26. 21:08Java

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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import java.util.Scanner;
 
public class Ex {
 
    public static void main(String[] args) {
        System.out.println("데이터 입력");
        Scanner s=new Scanner(System.in);
        
        while(s.hasNext()) {
            System.out.println(s.next());
        }
    }
 
}
import java.io.IOException;
import java.io.InputStream;
 
public class Ex2 {
 
    public static void main(String[] args) {
        
        /*
         * 기본 입력스트림(InputStream)
         * -가장 저수준의 입력 방식
         * read() 메서드를 사용하여 입력스트림으로 전달되는 데이터 중 1Byte를 읽어옴
         * 1)여러개의 데이터를 가져올 수 없음.(1Byte 만 읽어옴) = read(byte[] b) 사용하면 해결
         * 2) 문자 데이터의 경우 별도의 형변환 필요
         * 3) 한글 또는 한자 등의 2Byte문자들 처리 불가능
         * 
         * 
         */
        System.out.println("데이터를 입력하세요");
        
        //키보드로부터 입력을 받기 위해서는 System 클래스의 상수 in을 지정하여 입력
        //System.in의 데이터타입이 inputStream 타입이므로 InputStream 타입 변수에 전달
        //키보드 입력스트림과 연결됨
        
//        try {
//            InputStream is=System.in;//키보드로부터 입력받는 입력스트림 연결
//            int n=is.read();//키보드로부터 입력되는 데이터 중 1 Byte 읽어오기
////            System.out.println("입력데이터 : "+n);
//            System.out.println("입력데이터 : "+(char)n);//문자로 변환하여 출력
//            
//            //자바 I/O 사용시 자원반환 필수
//            is.close();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
        //-----------------------
        
        //try~resource 구문을 사용하면 별도의 closd() 메서드 호출이 필요없어짐
        
//        try (InputStream is = System.in) {
//            int n=is.read();
//            System.out.println("입력데이터 : "+(char)n);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
        //---------------------------
        
        //반복문을 사용하여 여러 바이트를 처리할 수 있다.
        try (InputStream is = System.in) {
            int n=is.read();
            
            while(n!=-1) {//-1 입력시 반복종료(Ctrl + Z 입력시 -1 이 입력됨)
                System.out.println("입력데이터 : "+n+", 문자로 : "+(char)n);
                n=is.read();// 다음 바이트 입력
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        
    }
 
}
 
import java.io.IOException;
import java.io.InputStream;
 
public class Ex3 {
 
    public static void main(String[] args) {
        /*
         * InputStream 클래스의 read(byte[] b)메서드를 사용하여
         * 여러개의 바이트를 한꺼번에 읽어오는 방법(=버퍼사용)
         * 1개이상의 바이트를 배열에 저장하므로 여러개의 바이트 입력 가능
         * 한글, 한자 등의 2Byte 단위 처리가 어려움
         * 문자 데이터의 경우 별도의 변환 필요
         * 여전히 저수준의 입력방법
         * 
         */
        
        System.out.println("데이터를 입력하세요.");
        
        byte[] b= new byte[10];
        
        try(InputStream is= System.in;){
            int read=is.read(b);//입력데이터를 읽어서 byte[] 타입 b에 저장
            //리턴되는 데이터는 입력된 바이트 갯수
            
            System.out.println(read);//입력된 바이트 갯수 출력
            
//            for(byte bb:b) {
//                System.out.println("입력데이터 : "+bb+", 문자로 : "+(char)bb);
//            }
//            System.out.println(new String(b,0,read));
            
            while(read>0) {//데이터 입력이 있을 경우 입력된 바이트 갯수는 0보다 큼
                System.out.println("읽은 갯수 : "+read+", 문자열로 : "+new String(b,0,read));
                read=is.read(b);//새로운 배열 읽어오기
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
 
}
 
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class Ex4 {
 
    public static void main(String[] args) {
        
        /*
         * InputStreamReader 객체를 활용한 char 단위 입력 처리
         * -InputStream 객체를 연결하여 char 단위로 처리하기 위해
         * InputStreamReader 객체를 생성하면서 생성자에 InputStream 객체 전달
         * 한글 ,한자 등 2Byte단위 데이터 처리가 가능해짐
         * 단, 1글자만 처리가 가능하며, 여전히 문자 변환이 필요함.
         */
        
        System.out.println("데이터를 입력하세요.");
        
//        try(InputStream is=System.in){
//            //InputStream 객체 (Byte 단위)를 char 단위로 처리하기 위해
//            //InputStreamReader 객체 생성 파라미터로 전달
//            InputStreamReader reader=new InputStreamReader(is);
//            int n=reader.read();//2Byte(char단위)읽어와서 int형 변수 n에 저장
//            System.out.println("입력데이터 : "+n+", 문자로 : "+(char)n);
//            
        //InputStreamReader 객체도 자원반환 필수!
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        
        //---------------------------------------
        char[] buffer=new char[10];//char 배열 10개 생성
        
        try(InputStreamReader reader=new InputStreamReader(System.in)){
            
            int n=reader.read(buffer);//2Byte(char단위)읽어와서 int형 변수 n에 저장
            
            while(n>0) {
                System.out.println("읽은 갯수 : "+n+", 문자열로 : "+new String(buffer,0,n));
                n=reader.read(buffer);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class Ex5 {
 
    public static void main(String[] args) {
        
        /*
         * 보조 스트림을 활용한 데코레이션 패턴 적용
         * BufferedReader 객체를 사용하여 입력스트림을 문자열 형태로 처리
         * 
         */
        
//        InputStream is=System.in;
//        InputStreamReader reader=new InputStreamReader(is);
        //위의 두 문장을 한문장으로 결합
//        InputStreamReader reader= new InputStreamReader(System.in);
//        
//        BufferedReader buffer=new BufferedReader(reader);
        //위의 모든 문장을 한 문장으로 결합
//        BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("데이터를 입력하세요.");
        
        
//        try(BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in))){
//            //BufferedReader 객체의 readLine() 메서드를 호출하여 한 문장 읽어오기
        // ㄹ턴타입이 String 이므로 문자열로 관리됨
//            String str=buffer.readLine();
//            System.out.println(str);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        
        //-----------------------------------------
        try(BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in))){
            //BufferedReader 객체의 readLine() 메서드를 호출하여 한 문장 읽어오기
            String str=buffer.readLine();
            while(str!=null) {//입력된 문자열이 null 이 아닐 동안 반복
                //CTRL + Z 가 null값 전달
                System.out.println(str);//한문장 출력
                str=buffer.readLine();// 다음 한문장 읽어오기
                
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
}
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class test5 {
 
    public static void main(String[] args) {
        
        //입력되는 모든 문장을 하나의 변수에 저장하면서
        // :wq 가 입력되면 입력을 중지하고 지금까지 입력된 모든 텍스트를 한꺼번에 출력하기
        System.out.println("데이터를 입력하세요.(중단은 :wq 입력)");
        
        
//        try(BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in))){
//            //BufferedReader 객체의 readLine() 메서드를 호출하여 한 문장 읽어오기
//            String str=buffer.readLine();
//            while(str!=null) {//입력된 문자열이 null 이 아닐 동안 반복
//                //CTRL + Z 가 null값 전달
//                System.out.println(str);//한문장 출력
//                str=buffer.readLine();// 다음 한문장 읽어오기
//                if(str.equals(":wq")) {
//                    
//                    break;
//                }
//            }
//            
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        
        //--------------------------------
        try(BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in))){
            String textData="";//전체 문자열 저장할 변수
            
            String str=buffer.readLine();
            while(!str.equals(":wq")) {
            textData+=str+"\n";//입력된 한 문장 저장(줄바꿈 추가 필요)
            str=buffer.readLine();//다음 한 문장 읽어오기
                
            }
            System.out.println("---------------");
            System.out.println(textData);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
}
 
 
cs

입력 데이터를 다루는 방법을 알아보았는데 처음엔 이게 무슨 이야기지 했었는데 시스템의 발전 상황을 쭈욱 설명을 들으며 해보니 이해가 되었다. 처음엔 텍스트도 깨지고 완벽하지 않은 상황이었지만 점점 단계를 올려가며 해보니 텍스트도 깨지지 않고 그대로 받을 수 있었다. Scanner 보다는 BufferedReader 가 더 많이 쓰이기도 하고 입력된 데이터를 안 깨어지고 변환을 잘 시켜 주기 때문에 잘 기억해 두어야겠다.