/** * Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"}, * this end of line marker is not included in the result. * * @return the next line from the input. * @throws IOException for underlying {@code InputStream} errors. * @throws EOFException for the end of source stream. */ //读取一行数据 // 从输入流里面读8192的数据到buf[]里面去,检查有没有换行符,有就输出,没有再new ByteArrayOutputStream // 类,循环的读数据到buf再写到output流里面去,一直读到文件末尾都没有换行符则抛出Exception public String readLine()throws IOException { synchronized (in) { if (buf == null) { thrownew IOException("LineReader is closed"); }
// Read more data if we are at the end of the buffered data. // Though it's an error to read after an exception, we will let {@code fillBuf()} // throw again if that happens; thus we need to handle end == -1 as well as end == pos. if (pos >= end) { fillBuf(); } // Try to find LF in the buffered data and return the line if successful. for (int i = pos; i != end; ++i) { if (buf[i] == LF) { int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i; String res = new String(buf, pos, lineEnd - pos, charset.name()); pos = i + 1; return res; } }
// Let's anticipate up to 80 characters on top of those already read. ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) { @Override public String toString(){ int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count; try { returnnew String(buf, 0, length, charset.name()); } catch (UnsupportedEncodingException e) { thrownew AssertionError(e); // Since we control the charset this will never happen. } } };
while (true) { out.write(buf, pos, end - pos); // Mark unterminated line in case fillBuf throws EOFException or IOException. end = -1; fillBuf(); // Try to find LF in the buffered data and return the line if successful. for (int i = pos; i != end; ++i) { if (buf[i] == LF) { if (i != pos) { out.write(buf, pos, i - pos); } pos = i + 1; return out.toString(); } } } } }
/** * Reads new input data into the buffer. Call only with pos == end or end == -1, * depending on the desired outcome if the function throws. */ privatevoidfillBuf()throws IOException { int result = in.read(buf, 0, buf.length); if (result == -1) { thrownew EOFException(); } pos = 0; end = result; }