본문 바로가기

개발/Java

[Java] 자바 - 데이터 입출력 / 스트림(Stream) / 바이트 스트림 / 문자 스트림

 

< 데이터 입출력 >

 

- IO(Input & Output)

- 프로그램상의 데이터를 외부매체(모니터, 스피커, 파일)로 출력하거나,

  입력장치(키보드, 마우스, 카메라, 마이크, 파일)로 입력받는 과정

 

 

< DAO >

 

- Data Access Object

- 데이터가 보관되어있는 공간에 직접 접근해서 데이터를 입출력하는 메소드들을 모아둔 클래스

- dao 패키지에 클래스 생성 

 

 

< 스트림 (Stream) >

 

- 입출력 장치에서 데이터를 읽고 쓰기 위해서 자바에서 제공하는 클래스

- 프로그램과 외부매체와의 통로

 

[ 특징 ]

- 단방향 : 입력용 스트림과 출력용 스트림이 따로 존재. 입출력 동시 불가

- 선입선출(FIFO) : 먼저 전달한 값이 먼저 나오게 됨 - 큐(Queue) 구조

                               (시간지연 문제가 발생할 수 있음)

 

[ 구분 ]

- 통로의 크기

바이트 스트림
(Byte Stream)
1Byte짜리가 이동할 수 있는 좁은 통로
[ 메소드명 ] 입력(XXXInputStream) / 출력(XXXOutputStream) 
문자 스트림
(Char Stream)
2Byte짜리가 이동할 수 있는 넓은 통로
[ 메소드명 ] 입력(XXXReader) / 출력(XXXWriter)

- 외부매체와의 직접 연결 여부

기반 스트림 외부매체와 직접적으로 연결되는 통로
보조 스트림 기반스트림만으로 부족한 성능을 향상시켜주는 용도로 만들어진 스트림
- 단독 사용 불가(기반스트림을 만들고 추가해주는 용도)

 

 

 < 바이트 스트림 >

 

> 출력 ( 프로그램 → 외부매체(파일) )

- FileOutputStream : 파일로 데이터를 출력할 때 1Byte 단위로 출력

- 한글은 2Byte이기 때문에 제대로 저장되지 않음

[ 순서 ]

1. FileOutputStream 객체 생성

- 해당 파일이 존재하지 않는 경우 : 파일 생성하며 연결

- 해당 파일이 존재하는 경우 : 해당 파일과 연결

   (파일명 뒤에 인자로 true를 넣어 이어서 작성할지, 덮어쓸지 옵션 지정 가능)

2. write()를 호출하여 데이터 출력

- ASCII코드표를 활용하여 0 ~ 127까지 숫자를 전달할 수 있음 (음수 전달 불가)

3. close()로 자원 반납

public void fileSave() {

    FileOutputStream fout = null;

    try {
        fout = new FileOutputStream("a_byte.txt"/*, true*/); // 예외처리 필요 (FileNotFoundException)
        // 생성자 호출시 옵션 지정 가능

        // 데이터 출력
        fout.write(97); // a // 예외처리 필요 (IOException)
        fout.write(98); // b
        fout.write(99); // c
        fout.write(100); // d

        byte[] arr = {101, 102, 103};
        fout.write(arr); // efg
        fout.write(arr, 1, 2); // fg
        // arr배열로부터 1번인덱스에서 2개 입력(슬라이싱 가능)

        fout.write('A');
        fout.write('B');
        fout.write('C');

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally { // 어떤 예외가 발생했든, 반드시 실행할 구문을 finally블럭 안에 넣어줌

        try { // 자원반납
            fout.close(); // 예외처리 필요 (IOException)
        } catch(IOException e) {
            e.printStackTrace();
        }
    }	
}

> 입력 ( 프로그램 ← 외부매체(파일) )

- FileInputStream : 파일로부터 데이터를 입력받을 때 1Byte단위로 입력

[ 순서 ]

1. FileInputStream 객체 생성

2. read() 호출하여 데이터 입력

- 읽어올 데이터가 없으면 -1을 반환함

- 반복문 while 사용 가능

3. close()로 자원 반납

public void fileRead() {

    FileInputStream fis = null;

    try { 	
        fis = new FileInputStream("a_byte.txt"); // 예외처리 필요 (FileNotFoundException)

        System.out.println(fis.read()); // 예외처리 필요 (IOException)
        System.out.println(fis.read());

        int value = 0;
        while((value = fis.read()) != -1) { // 변수에 값을 담으면서 조건문 확인
            System.out.println(value);
        }
        
    } catch(FileNotFoundException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    } finally {

        try {
            fis.close(); //  예외처리 필요 (IOException)
        }
        catch(IOException e) {
            e.printStackTrace();
        }			
    }
}

 

 

< 문자 스트림 >

 

> 출력 ( 프로그램 → 외부매체(파일) )

- FileWriter : 파일로 데이터를 출력할 때 2Byte 단위로 출력

- 바이트 스트림과 사용은 동일

[ 순서 ]

1. FileWriter 객체 생성

2. write()를 호출하여 데이터 출력

3. close()로 자원 반납

public void fileSave() {

    FileWriter fw = null;

    try {

        fw = new FileWriter("b_char.txt"); // 예외처리필요 (IOException)

        fw.write("한글 출력 가능");
        fw.write("B");
        char[] arr = {'a', 'b', 'c', 'd'};
        fw.write(arr); // 배열 출력 가능

    } catch(IOException e) {
        e.printStackTrace();
    } finally {
        
        try { // 자원 반납
            fw.close(); // 예외처리필요 (IOException)
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

> 입력 ( 프로그램 ← 외부매체(파일) )

- FileReader : 파일로부터 데이터를 입력받을 때 2Byte단위로 입력

- 바이트 스트림과 사용은 동일

[ 순서 ]

1. FileReader 객체 생성

2. read() 호출하여 데이터 입력

- 읽어올 데이터가 없으면 -1을 반환함

- 반복문 while 사용 가능

3. close()로 자원 반납

public void fileRead() {

    FileReader fr = null;

    try {
        fr = new FileReader("b_char.txt"); // 예외처리 필요 (FileNotFoundException)
        
        System.out.println(fr.read()); 

        // 반복문 사용
        int value = 0;
        while ((value = fr.read()) != -1) { // 값이 날아가지 않도록 변수에 담아서 비교
            System.out.print((char)value);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        try {
            fr.close(); // 예외처리 필요 (IOException)
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}