개발/java

필터 스트림

나태쿤 2021. 3. 18. 17:20
728x90

java.io의 입력,출력 스트림들은 다음과 같이 두가지로 분류할 수 있다.

 

1. 기본 스트림

:외부 데이터와 직접 연결되는 스트림 

 

2. 필터 스트림

:기본 스트림에 추가로 사용할 수 있는 스트림, 그러니까 혼자 못사용한다

:사용하는 이유는 외부 데이터와 입출력 작업시에 편리한 기능을 사용하려고이다.

필터 스트림에는 BufferedReader라는 외부 데이터와 프로그램 사이에 Buffer를 사용한다

버퍼는 외부로부터 읽은 데이터를 잠시 저장되는 공간이다.

그리고 1바이트씩이 아닌 1줄 단위로 데이터를 읽을 수 있는

readLine()메서드를 제공하기에 더욱 편리하다.

 

예제 코드는 다음과 같다.

 

 

 

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
package com.ruby.java.ch12;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
public class Test04 {
 
    public static void main(String[] args) {
        byte[] arr = null;
        try(BufferedInputStream in = new BufferedInputStream(new FileInputStream("a.txt"));
            ByteArrayOutputStream out = new ByteArrayOutputStream();)    {
            
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            
            arr = out.toByteArray();
            String s = new String(arr);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        try(BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream("a2.txt"))) {
            
            bo.write(arr);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
//        try(BufferedInputStream in = new BufferedInputStream(new FileInputStream("a.txt"));
//            ByteArrayOutputStream out = new    ByteArrayOutputStream();) {
//            
//            byte[] buf = new byte[1024];
//            int len = 0;
//            while((len = in.read(buf)) != -1) {
//                out.write(buf, 0, len);
//            }
//            byte[] arr = out.toByteArray();
//            String s = new String(arr);
//            System.out.println(s);
//
//            
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        
        
    }
 
}
cs

결과론 적으로 a.txt를 입력받아 a2.txt를 출력한다. 즉 생성한다.

728x90