- 데이터를 하나씩 전송하는 것이 아니라 모아서 한번에 전송하는 기능을 제공하는 클래스
- 앞에 Buffered가 붙은 클래스를 사용하면 알아서 버퍼 방식이 적용된다
- BufferedReader/Writer : 버퍼 기능 + char 단위 입출력
- BufferedInputStream/OutputStream : 버퍼 기능 + byte 단위 입출력
- InputStreamReader : byte단위의 스트림을 char단위로 업그레이드 해주는 클래스

 

Long start, end;

한 글자씩 출력해주는 버퍼 생성 

File testFile = new File("myfiles/test.txt");
		
long start, end;

 

비교를 하기 위한 시간초 세기

start = System.currentTimeMillis();

 

try (
        FileReader in = new FileReader(testFile);
) {
    int ch;
    while ((ch = in.read()) != -1) {
        System.out.print((char)ch);
    }
} catch (IOException e) {
    e.printStackTrace();
}

 

end - start 로 걸린 시간 측정

end = System.currentTimeMillis();
long time1 = end - start;
System.out.println("걸린시간1: " + time1 + "ms");

 

 

 

똑같이 시간을 재는 Long 타입 time2 선언

long time2 = end - start;

start = System.currentTimeMillis();
try (
        FileReader fin = new FileReader(testFile);
        BufferedReader in = new BufferedReader(fin);
) {

 

Buffered 스트림에는 한 줄씩 읽는 기능이 추가되어 있다
읽을것이 있으면 읽을 내용을 반환, 없으면 null을 반환

String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
end = System.currentTimeMillis();

 

System.out.println("걸린시간2: " + time2 + "ms");

 

한줄씩 읽을 경우 0ms

 

Scanner 대신 Buffered 클래스를 사용하여 콘솔로부터 입력받기
(Scanner는 들어오는 문자에 대한 정규표현식 검사를 하기 때문에 속도가 훨씬 느리다)

try (
    InputStreamReader in = new InputStreamReader(System.in);
    BufferedReader sc = new BufferedReader(in);
) {
    while (true) {
        if (sc.readLine().equals("exit")) {
            break;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println("걸린시간3: " + time3 + "ms");

 

'JAVA' 카테고리의 다른 글

Network  (0) 2024.07.08
PrintStream  (0) 2024.07.05
AutoClose  (0) 2024.07.01
File  (0) 2024.06.29
JavaIO  (0) 2024.06.15

+ Recent posts