readline() returns null in Java

后端 未结 2 1929
-上瘾入骨i
-上瘾入骨i 2021-01-22 07:54

I\'m trying to read the stdin in my Java program. I\'m expecting a series of numbers followed by newlines, like:

6  
9  
1  

When providing th

2条回答
  •  轮回少年
    2021-01-22 08:34

    Not really a new answer to this question, but I wanted to clear up confusion in the comments about why the original code behaved as it did (I can't comment because I'm new to ST and haven't garnered reputation points).

    The null result has nothing to do with garbage collection. The following program suffers exactly the same fate even though both readers still live, accessible objects:

    BufferedReader r1 = new BufferedReader(new InputStreamReader(System.in));
    System.out.println(r1.readLine());
    BufferedReader r2 = new BufferedReader(new InputStreamReader(System.in));
    System.out.println(r2.readLine());
    

    It all comes down to what "Buffered" means in BufferedReader. It's a Reader that includes internal buffering. The internal buffering usually significantly improves the efficiency of operations on the underlying stream, e.g. by attempting to read a full buffer's worth each time, rather than nickle-and-diming the stream to death getting a few bytes here and a few there.

    So what happens when you create the first BufferedReader on stdin and read a line from it? That BufferedReader reads a buffer-full from the stream, detects the end of line, returns the first line, and hangs on to the rest of the buffer to fill its next request. That leaves the underlying stream positioned beyond the end of that first line. And if your input is small, it could easily be positioned at EOF.

    So now you come along and create a second BufferedReader atop the same stream - which is at EOF - and attempt to get a line. The second BufferedReader attempts to read from the underlying stream and detects EOF, so readLine returns null.

提交回复
热议问题