Java readLine source code analysis


readLine

  • Reader BufferedReader class inherits from, and a new method of reading row: String readLine()This method returns a string that does not contain the content of diverted terminator, and if the end of the stream is null;
  • Use the following examples:
public class Test {
    public static void main(String[] args) throws IOException {
        // 创建流对象
        BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\80626\\Desktop\\1.txt"));
        // 定义字符串,保存读取的一行文字
        String line = null;
        // 循环读取,读取到最后返回null
        while ((line = br.readLine()) != null) {
            System.out.print(line);
            System.out.println("------");
        }
        // 释放资源
        br.close();
    }
}

The method 1. API

    public String readLine() throws IOException {
        return readLine(false);
    }
  • In fact, calling the String readLine(boolean ignoreLF)method, ignoreLF = trueignoring the next newline '\n';
	/** If the next character is a line feed, skip it */
    private boolean skipLF = false;
  • BufferedReader class private variables skipLF = false;
  • Read the instructions shows that readLine()the main function of the method is to read a line of text, line feeds '\n', carriage return '\r', line feed after a carriage return, or reach the end of the file is considered to be terminated. It returns a string containing the contents of the line, it does not include any line terminating character , if it reaches the end of the stream without any characters read, compared null. readLine()The method is as follows:
	String readLine(boolean ignoreLF) throws IOException {
        StringBuffer s = null;
        int startChar;

        synchronized (lock) {
            ensureOpen();
            boolean omitLF = ignoreLF || skipLF;

        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')) {
                        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 StringBuffer(defaultExpectedLineLength);
                s.append(cb, startChar, i - startChar);
            }
        }
    }
  • Read BufferedReader class, there is a private class variables defaultCharBufferSize:
	private static int defaultCharBufferSize = 8192;
  • Visible, readLine()called an infinite loop, will continue to add data to Buffer, if you do not specify the size of Buffer, the readLine()Buffer used are 8192 characters (8 * 1024), before reaching the Buffer size, only encountered /r, /n, /r/nwill not return ;
  • When using data stream socket or the like, should be avoided readLine(), in order to avoid waiting for a carriage return and line feed or has been blocked;

2. Network Mode Considerations

  • On the network readLine()is blocking mode, that is, if readLine()not read data, it will always be blocked, instead of returning null, so if you want to perform after the while loop shape-related operation is not possible, because it is a dead cycle, once the data is not read, it began to clog, and therefore can never be executed outside shape while loop operation, the operation should be placed inside the while loop;
  • Inside the while loop to determine readLine()!= nullwhen to assign a String, because if not null, then this time the line has been read. If while (br.readLine()!=null), then the following can not get to the line again, so it should be used while ((line = br.readLine())!=null){};
  • readLine()By one of the following characters can be considered a discontinued line: newline '\n', carriage return '\r'followed immediately or after a carriage return line feed, so we add these identifiers later when sending data again, otherwise the program will be blocked. This directly using the following method: PrintStream ps = new PrintStream(socket.getOutputStream(), true, "UTF-8");ps.println();, ps.println()it has been included for the trip, so do not use print(), if necessary to be followed by the newline character;
  • readLine()Only an abnormality occurs in the data stream or the other end is close()when off, does not return nulla value.

Recommended reading: the Java Stream buffer buffered stream >>>

Published 281 original articles · won praise 285 · views 10000 +

Guess you like

Origin blog.csdn.net/Regino/article/details/105060868