BufferedReader와 IOException의 관계 !?

서은경·2022년 11월 22일
0

Java

목록 보기
18/19

요즘 알고리즘 공부를 빡시게 하면서 BufferedReader 를 많이 쓰는데 br.readLine() 을 쓰면 꼭 빨간줄이 뜨면서 IOException 처리를 해주라고 한다.

Unhandled exception: java.io.IOException

하라니까 하긴 한다만..

왜 ?!?!?!?!?

왜 IOException 처리를 해줘야하는지 궁금해서 찾아봤다.
결론부터 말하자면

InputStream==null 일때 생길 장애를 미연에 방지하기 위함!

synchronized(lock)을 통해 lock을 걸어 동시호출을 막는다.
ensureOpen() 함수를 보면 in이 null인지를 체크하여 IOException 을 던진다. 여기서 in이란 InputStreamReader 이 되는데 해당 자원이 없는데 강제로 read 시킬 경우 장애가 생기기 때문에 IOException 처리를 해주는 것이었다!

혹여 내가 이해할 수 있나 해서 까본 readLine() 소스~

/**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), a carriage return
     * followed immediately by a line feed, or by reaching the end-of-file
     * (EOF).
     *
     * @param      ignoreLF  If true, the next '\n' will be skipped
     * @param      term      Output: Whether a line terminator was encountered
     *                       while reading the line; may be {@code null}.
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached without reading any characters
     *
     * @see        java.io.LineNumberReader#readLine()
     *
     * @throws     IOException  If an I/O error occurs
     */
    String readLine(boolean ignoreLF, boolean[] term) throws IOException {
        StringBuilder s = null;
        int startChar;

        synchronized (lock) {
            ensureOpen();
            boolean omitLF = ignoreLF || skipLF;
            if (term != null) term[0] = false;

        bufferLoop:
            for (;;) {

                if (nextChar >= nChars)
                    fill();
                if (nextChar >= nChars) { /* EOF */
                    if (s != null && s.length() > 0)
                        return s.toString();
                    else
                        return null;
                }
                boolean eol = false;
                char c = 0;
                int i;

                /* Skip a leftover '\n', if necessary */
                if (omitLF && (cb[nextChar] == '\n'))
                    nextChar++;
                skipLF = false;
                omitLF = false;

            charLoop:
                for (i = nextChar; i < nChars; i++) {
                    c = cb[i];
                    if ((c == '\n') || (c == '\r')) {
                        if (term != null) term[0] = true;
                        eol = true;
                        break charLoop;
                    }
                }

                startChar = nextChar;
                nextChar = i;

                if (eol) {
                    String str;
                    if (s == null) {
                        str = new String(cb, startChar, i - startChar);
                    } else {
                        s.append(cb, startChar, i - startChar);
                        str = s.toString();
                    }
                    nextChar++;
                    if (c == '\r') {
                        skipLF = true;
                    }
                    return str;
                }

                if (s == null)
                    s = new StringBuilder(defaultExpectedLineLength);
                s.append(cb, startChar, i - startChar);
            }
        }
    }

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), a carriage return
     * followed immediately by a line feed, or by reaching the end-of-file
     * (EOF).
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached without reading any characters
     *
     * @throws     IOException  If an I/O error occurs
     *
     * @see java.nio.file.Files#readAllLines
     */
    public String readLine() throws IOException {
        return readLine(false, null);
    }

0개의 댓글

관련 채용 정보