InputStream, OutputStream

이규은·2021년 10월 25일
0

자바 I/O

목록 보기
4/7

InputStream

바이트 기반 입력 스트림의 최상위 추상클래스이다.
파일 데이터를 읽거나 네트워크 소케을 통해 데이터를 읽거나 키보드에서 입력한 데이터를 읽을 때 사용한다.
InputStream은 읽기에 대한 다양한 추상 메소드를 정의해 두었다
InputStream의 추상메소드를 오버라이딩하여 목적에 따라 데이터를 입력 받을 수 있다.

InputStream의 기본 메서드

public class InputStreamStudy {
    public static void main(String[] args) throws IOException {
        byte[] bytes = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        InputStream inputStream = new ByteArrayInputStream(bytes);
        int data;

        while ((data = inputStream.read()) != -1) {
            System.out.print(data);
        }
    }
}


1바이트씩 읽고 읽은 바이트를 반환한다.

public class InputStreamStudy {
    public static void main(String[] args) throws IOException {
        byte[] bytes = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        InputStream inputStream = new ByteArrayInputStream(bytes);

        int len = 3;
        int readCnt = 0;
        byte[] buffer = new byte[len];

        while((readCnt = inputStream.read(buffer)) != -1) {
            for (int i = 0; i < readCnt; i++) {
                System.out.print(buffer[i]);
            }
            System.out.println();
        }
    }
}


byte buffer[] 만큼 읽고 읽은 데이터 수를 반환한다.
여러 바이트씩 읽기 때문에 한 바이트씩 읽는거 보다 빠르다.

public class InputStreamStudy {
    public static void main(String[] args) throws IOException {
        byte[] bytes = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        InputStream inputStream = new ByteArrayInputStream(bytes);

        int len = 4;
        int readCnt = 0;
        int offset = 0;
        byte[] buffer = new byte[1024];

        while((readCnt = inputStream.read(buffer, offset, len)) != -1) {
            offset += readCnt;
            for (int i = 0; i < offset; i++) {
                System.out.print(buffer[i]);
            }
            System.out.println();
        }
    }
}


데이터를 4개씩 읽으며 다시 읽을때 배열의 처음위치가 아닌 buffer[offset] 부터 읽는다.
offset은 데이터 수 만큼 증가한다.

OutputStream

public class OutputStream {
    public static void main(String[] args) throws IOException {
        byte[] bytes = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

        File file = new File("D://write_test.txt");
        FileOutputStream outputStream = new FileOutputStream(file);

        for (byte b : bytes) {
            outputStream.write(b);
        }
        outputStream.close();
    }
}

바이트 배열을 write_test.txt. 파일에 write한다.

profile
안녕하세요

0개의 댓글