Notice
Recent Posts
Recent Comments
Link
«   2026/03   »
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
Tags
more
Archives
Today
Total
관리 메뉴

brograming

[입출력] 바이트 기반 스트림 본문

[JAVA]

[입출력] 바이트 기반 스트림

brograming 2023. 4. 17. 23:17

입출력 I/O

Input과 Output의 약자로 입출력이라고 한다.  컴퓨터 내부 또는 외부의 장치와 프로그램간의 데이터를 주고받는 것

 

입력 스트림 : 밖에서 프로그램쪽으로 데이터의 흐름을 소프트웨어로 구현한 모듈

출력 스트림 : 프로그램에서 밖으로 데이터의 흐름을 소프트웨어로 구현한 모듈

 

스트림

스트림이란 데이터를 운반하는데 사용되는 연결통로이다.

단방향 통신만 가능해서 하나의 스트림으로 입력과 출력을 동시에 처리불가하다.

동시에 수행하려면 입력 스트림과 출력 스트림 모두 필요하다.

스트림은 먼저 보낸 데이터를 먼저 받게 되는 FIFO  방식으로 이루어진다.

 

바이트 기반 스트림

 

 

ㆍ바이트 스트림 : 한 바이트식 읽고 씀. 그림, 멀티미디어, 문자 등 모든 종류의 데이터를 입출력할 때 사용

 

             - InputStream : FileInputStream(파일에서 1바이트씩 읽는 스트림)

                int read() : 1 바이트 읽어서 int 타입으로 반환

                int read( byte[] ) : 파라미터로 넣은 배열 크기만큼 읽어서 배열에 저장. 반환값은 읽은 바이트 수를 반환.

                int read( byte[], offs, size ) : size만큼 읽어서 배열에 저장. 저장 시작 위치를 offs로. 반환값은 읽은 바이트 수를 반환.

 

             - OutputStream : FileOutputStream(파일에 1바이트씩 출력 스트림)

                void write(int ch) : 1 바이트(ch) 출력 

                void write( byte[] ) : 배열 크기만큼 배열요소들을 출력. 출력한 바이트 수 반환

                void write( byte[], offs, size) : byte[] 배열에서 offs위치부터 size크기만큼을 출력. 출력한 바이트 수 반환

 

 

FileInputStream와 FileOutPutStream

 

read()의 반환값이 int형 (4byte)이지만 입력값 없음을 알리는 -1을 제외하면 0 ~ 255(1byte)범위의 정수값이기 때문에, char형 (2byte)로 변환해도 손실은 없다. 

 

read( ) 

public class FileInputStreamTest {

    public static void main(String[] args) {
        try {
            //생성자에 지정한 경로의 파일에서 한 바이트식 읽을 수 있는 스트림 생성
            FileInputStream fi = new FileInputStream("src/입출력스트림/files/a.txt");
            int ch;
            
            while ((ch = fi.read())!= -1) {      //EOF(End Of File) : -1
            System.out.print((char)ch);    
            }
            fi.close(); // 스트림 닫음
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

 

read(byte[ ] ) 

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
public class FileInputStreamTest2 {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            //사용할 inputstream 생성
            FileInputStream fi = new FileInputStream("src/입출력스트림/files/a.txt");
            //읽은 값 담을 배열
            byte[] buf = new byte[10]; // buf에는 읽은 데이터 저장
            int size = 0;  // read(byte[]) 반환값 담을 변수. 방금 읽은 바이트 수 반환 
            while((size = fi.read(buf)) > 0) {  // 읽은 바이트 수가 0보다 크면 한 바이트라도 읽은 것이므로 출력
               // ↑ new byte[10]배열 크기를 10으로 정했기 때문에 한번에 10byte씩 읽는다. 읽은 데이터를 buf에 저장.
System.out.print(new String(buf));
                //배열 buf를 ' '로 초기화
                Arrays.fill(buf, (byte)' ');  // Arrays.fill() 배열을 지정한 값((byte)' ')으로 채움
            }
            fi.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
}
cs

write( byte[ ])

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
public class FileOutputStreamTest {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            // 1바이트씩 파일에 출력하는 스트림
            // 쓰기용 파일은 있으면 그 파일에 덮어쓰기. 없으면 자동으로 생성하여 출력
            FileOutputStream fo = new FileOutputStream("src/입출력스트림/files/c.txt");
            
            byte[] buf = "hello java stream".getBytes();  //getBytes() : 문자열을 바이트배열로 반환
//            for(int i = 0; i< buf.length; i++) {
//                fo.write(buf[i]);  // for문으로 한글자 한글자씩 읽기. int write()
//            }
            fo.write(buf);   // 통채로 읽기. int write(byte[]) > 더 효율적임
fo.flush();
            fo.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
cs

'[JAVA]' 카테고리의 다른 글

자바 jdk-17 설치 및 환경변수 설정  (0) 2023.07.25
char 배열을 문자열로 변환 String.valueOf() / new String()  (0) 2023.04.17
[입출력] 문자 기반 스트림  (0) 2023.04.17
[Collection] ArrayList  (0) 2023.04.16
[Collection] Map  (0) 2023.04.16