[자바] BufferedWriter 에서는 왜 정수를 String 으로 변환해서 출력해야만 하는가?

박상준·2024년 6월 15일
0

코딩테스트

목록 보기
19/19

BufferWriter 의 write 메서드

public void write(int c) throws IOException {
    synchronized (lock) {
        ensureOpen();
        if (nextChar >= nChars)
            flushBuffer();
        cb[nextChar++] = (char) c; // 여기서 정수 65 값은 아스키 'a' 로 변환되어 저장된다.
        //bufferedWriter 는 내부 버퍼배열이 char 형태로 기록된다.
    }
}
  • 그래서 int 값은 String 으로 변환하여,
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        bw.write(String.valueOf(65));
    }
  • 요런 식으로 String “65” 를 버퍼에 기록하는 것이다.
  • 디버깅을 해보면

public void write(String s, int off, int len) throws IOException {
    synchronized (lock) {
        ensureOpen();

        int b = off, t = off + len;
        while (b < t) {
            int d = min(nChars - nextChar, t - b);
            s.getChars(b, b + d, cb, nextChar);
            b += d;
            nextChar += d;
            if (nextChar >= nChars)
                flushBuffer();
        }
    }
}
  • 결국 이 write 는 타게 되는데
    • 현재 버퍼상에서 남은 크기와 남은 String -을 char[] 로 고려했을때의 크기와 비교하여 작은 값에 대해,
    • 버퍼에 char 를 쓴다.
    • 현재 8192 의 배열에 [’6’,’5’,….] 를 최종적으로 쓰게되는 것이다.
profile
이전 블로그 : https://oth3410.tistory.com/

0개의 댓글