[Java] InputStream, InputStreamReader, BufferedReader, Scanner

유빈·2024년 10월 1일
0

생존 Java

목록 보기
1/3
post-thumbnail

1. Stream

  • 데이터가 연속적으로 존재한다는 것을 표현한 객체
  • byte의 연속된 집합
  • 사용자의 키보드 입력, 파일 데이터, HTTP 송수신 데이터 등이 모두 Stream으로 간주되어 STream 관련 API를 통해서 데이터를 처리하게 됨


2. InputStream

  • 1 byte의 int형의 아스키 코드값을 값으로 저장함
package prac_IO;

import java.io.InputStream;

public class prac01 {
    public static void main(String[] args) {
        try {
            InputStream in = System.in;  // 키보드로부터 입력받을 수 있음
            int a;
            a = in.read();  // 입력으로부터 한 바이트를 읽어 a에 저장

            System.out.println(a);  // 입력한 문자의 ASCII 값을 출력
            // 아무것도 입력 X = -1 반환
        } catch (Exception e) {}  // 예외가 발생하면 catch문에서 처리하지만, 현재 아무 처리 X
    }
}

  • read(): byte 크기만큼 읽어들임

package prac_IO;

import java.io.IOException;
import java.io.InputStream;

public class prac02 {
    // 입출력 작업에서 발생할 수 있는 IOException을 던짐
    public static void main(String[] args) throws IOException {
        InputStream inputStream = System.in;

        byte[] bytes = new byte[3];
        inputStream.read(bytes);  // byte 단위로, 사용자의 입력을 bytes 배열에 읽어들임

        System.out.println(bytes[0]);
        System.out.println(bytes[1]);
        System.out.println(bytes[2]);
    }
}


3. InputStreamReader

  • byte 대신 char 형태로 읽어옴
  • ASCII가 아닌 문자열로 출력 가능
  • String 객체로 변환 가능
  • read()
package prac_IO;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class prac03 {
    public static void main(String[] args) throws IOException {
        InputStream inputStream = System.in;
        InputStreamReader reader = new InputStreamReader(inputStream);
        
        // 위의 두 줄을 다음과 같이 줄여쓰기 가능
        // InputStreamReader reader = new InputStreamReader(System.in);

        char[] chars = new char[3];
        reader.read(chars);  // char형 문자를 하나씩 읽어들임 

        System.out.println(chars);
    }
}


4. BufferedReader

InputStream, InputStreamReader는 각각 byte, char형으로 읽어들일 수 있었다면, BufferedReader는 \n과 같이 엔터를 치기 전까지 또는 내용이 너무 길어서 Stream이 꽉차 null을 반환하기 전까지 모든 값을 저장한다.

  • readLine()

inputStream -> inputStreamReader -> BufferedReader 순서대로 사용


package prac_IO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class prac04 {
    public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(reader);

        String str = br.readLine();

        System.out.println(str);
    }
}

많은 데이터를 입력받는 경우에는 InputStreamReader는 Scanner보다 메모리 사용면에서 효율적이다.



5. Scanner

  • next(): 단어 1개
  • nextLine(): 라인 1줄
  • nectInt(): 정수값만 읽고, 문자를 입력하면 InputMismatchException 반환

package prac_IO;

import java.util.Scanner;

public class prac05 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(sc.next());
        System.out.println(sc.nextLine());
        System.out.println(sc.nextInt());
    }
}


출처: 컴퓨터 탐험가 찰리 - "자바 입력"

profile
🌱

0개의 댓글