Notice
Recent Posts
Recent Comments
Link
관리 메뉴

개발자되기 프로젝트

바이트 단위 입출력 스트림 본문

Java/다양한 기능

바이트 단위 입출력 스트림

Seung__ 2021. 10. 31. 16:06

1. InputStream


  • 바이트 단위 입력 스트림 중 최상위 추상 클래스
  • 많은 추상 메서드가 선언되어 있고 이를 하위 스트림이 상속받아 구현함
  • 주요 하위 클래스
스트림 클래스 설명
FileInputStream 파일에서 바이트 단위로 자료를 읽습니다.
ByteArrayInputStream byte 배열 메모리에서 바이트 단위로 자료를 읽습니다.
FilterInputStream 기반 스트림에서 자료를 읽을 때 추가 기능을 제공하는 보조 스트림의 상위 클래스
  • 주요 메서드
    • Stream은 close 필요함(System은 안해도 됨)
메서드 설명
int read() 입력 스트림으로부터 한 바이트의 자료를 읽습니다. 읽은 자료의 바이트 수를 반환합니다.
int read(byte b[]) 입력 스트림으로 부터 b[] 크기의 자료를 b[]에 읽습니다. 읽은 자료의 바이트 수를 반환합니다.
int read(byte b[], int off, int len) 입력 스트림으로 부터 b[] 크기의 자료를 b[]의 off변수 위치부터 저장하며 len 만큼 읽습니다. 읽은 자료의 바이트 수를 반환합니다.
void close() 입력 스트림과 연결된 대상 리소스를 닫습니다.

 

 

 

2. FileInputStream 예제 : 한 바이트 씩 읽기


  • project에 "input.txt" 파일 생성.
  • 파일을 불러와서 한 바이트씩 출력하는 테스트 코드.
  • read는 int를 반환하므로 char로 캐스팅.
public class FileInputStreamTest {

    public static void main(String[] args) {

        FileInputStream fis = null;

        try {
            fis = new FileInputStream("input.txt");
            System.out.println((char) fis.read());
            System.out.println((char) fis.read());
            System.out.println((char) fis.read());

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

            try {
                fis.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }catch (Exception exception){
                System.out.println(exception.getMessage());
            }
        }finally {

            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception exception){
                System.out.println(exception.getMessage());
            }
        }


        System.out.println("end");
    }

}

 

 

 

 

3. FileInputStream 예제 : 파일의 끝까지 한 바이트 씩 읽기


  • read()는 파일 끝에서 -1을 반환함.
public class FileInputStreamTest2 {

    public static void main(String[] args) {

        int i;
        //리소스를 try내부에 선언해 주면 close별도로 안해줘도 됨.
        try(FileInputStream fis = new FileInputStream("input.txt")) {

            while ((i = fis.read()) != -1){
                System.out.print((char) i);
            }
            System.out.println("");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("end");
    }

}

 

 

4. FileInputStream 예제


  • 파일에서 바이트 배열로 자료 읽기(배열에 남아있는 자료가 있을 수 있음! 주의!)
  • read(byte b[ ])
read(byte b[])
Params: b – the buffer into which the data is read.
Returns: the total number of bytes read into the buffer,
            or -1 if there is no more data because the end of the file has been reached.
  • read ()에 버퍼를 넣어서 사용하면 됨.
public class FileInputStreamTest3 {

    public static void main(String[] args) {

        int i;
        //리소스를 try내부에 선언해 주면 close별도로 안해줘도 됨.
        try(FileInputStream fis = new FileInputStream("input2.txt")) {

           byte[] bs = new byte[10];
           // byte 수
           while ((i = fis.read(bs)) != -1){
               for (byte b : bs) {
                   System.out.print((char) b);
               }
               System.out.println(" : " + i + "바이트 읽음");
           }
            System.out.println("");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("end");
    }

}
  • 주의 : 버퍼를 사용하는 경우 이전에  읽은 데이터가 남아있을 수 있음.
    • 이번 경우는 마지막에 6바이트만 새로 읽는데, 이전에 읽은 QRST가 그대로 보여짐.

  • 그럼 어떻게 하지???
    • 새로 읽은 만큼만 사용하면됨. read는 읽을 byte 수를 return 해줌.
  • 버퍼를 사용하는 경우 새로 읽은 byte수를 확인해서 새로 읽은 데이터만 활용하자.
public class FileInputStreamTest3 {

    public static void main(String[] args) {

        int i;
        //리소스를 try내부에 선언해 주면 close별도로 안해줘도 됨.
        try(FileInputStream fis = new FileInputStream("input2.txt")) {

           byte[] bs = new byte[10];
           // byte 수
           while ((i = fis.read(bs)) != -1){
               for (int j = 0; j < i; j++) {
                   System.out.print((char) bs[j]);
               }
               System.out.println(" : " + i + "바이트 읽음");
           }
            System.out.println("");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("end");
    }

}

 

 

5. GitHub : 211031 I/O Stream


 

GitHub - bsh6463/various_functions

Contribute to bsh6463/various_functions development by creating an account on GitHub.

github.com

 

'Java > 다양한 기능' 카테고리의 다른 글

문자단위 입출력 스트림  (0) 2021.10.31
바이트 단위 출력 스트림  (0) 2021.10.31
표준 입출력 스트림  (0) 2021.10.31
자바 입출력을 위한 I/O Stream  (0) 2021.10.31
사용자 정의 예외 클래스 활용  (0) 2021.10.31
Comments