[Java] Scanner vs BufferedReader

2024. 1. 7. 19:48Java

결과적으로 BufferdReader가 더 유리하다.

 

첫번째 이유는 BufferedReader는 Scanner의 데이터를 읽을때 발생하는 문제가 없다.

Scanner의 문제

- nextX에 해당하는 7개의 메소드는 개행이나 공백 전까지만 읽는다. (nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next())

- nextLine은 개행까지를 읽는다.

- 만약 다음과 같은 코드가 있다고 하자.

import java.util.Scanner;

class Solution
{
    public static void main(String args[]) throws Exception {
        Scanner sc = new Scanner(System.in);
        int T;
        T = sc.nextInt();
        String string = sc.nextLine();
        System.out.println("T = " + T);
        System.out.println("string = " + string);
    }
}

- 우리가 보통 원하는 건 T에 대한 값을 넣고 엔터 누르고 string에 대한 값을 넣는 것이다. 하지만 이렇게 되면 다음과 같은 결과가 나온다.

7
T = 7
string =

- 즉, 개행이 첫번째 줄에 남아있기 때문에 string 값이 \n이 되는 것이다.

- 이걸 해결하려면 nextLine을 하나더 넣어주면 된다. 그러면 남은 개행의 잔여로 인한 nextLine이 소비가 되어서 값을 입력할 수 없는 문제를 극복할 수 있다.

 

하지만 bufferedReader는 이러한 문제가 없다.

그 외 Scanner보다 bufferdReader를 사용해야 하는 이유는 다음과 같다.

두번째로 bufferdReader는 값을 파싱하는데 시간이 소모되는 Scanner와 달리 String으로 가지고 오기 때문에 조금 더 빠르다.

세번째로 bufferdReader(8KB)가 Scanner(1KB)의 버퍼 크기보다 더 크다

네번째로 bufferdReader는 동기적이라서 여러 쓰레드를 통한 구현이 가능해진다. (그러나 IO 작업을 멀티쓰레드로 하는건 비추천이다. 왜냐하면 IO는 CPU가 아니기 때문이다. 이럴 때는 보통 하나의 쓰레드로 데이터를 읽어와 produer/consumer queue에 저장하고 여러개의 쓰레드가 queue에서 데이터를 꺼내와서 사용하는 producer-consumer 패턴을 사용한다고 한다.)

 

Reference


https://www.geeksforgeeks.org/difference-between-scanner-and-bufferreader-class-in-java/

 

Difference Between Scanner and BufferedReader Class in Java - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

https://stackoverflow.com/questions/30168837/multi-thread-bufferedreader-for-reading-txt

 

Multi-Thread BufferedReader for reading .txt

I'm wanting to read the line of a .txt do the task, and move on to the next line. To make the program quicker, I want to multi-thread so each thread tries a line. The problem is, I don't want the

stackoverflow.com