readline() returns null in Java

后端 未结 2 1904
-上瘾入骨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.

    0 讨论(0)
  • 2021-01-22 08:36

    That you get a null indicates that the relevant Reader objects reached an EOF (end of file), or in other words that they can't get any more standard input. Now the obvious issues with your code are:

    1. Each method call to readLineFromStdIn() will create a new BufferedReader.
    2. Each such BufferedReader will be “competing” with each other for the same, shared input from System.in
    3. And none of these BufferedReader objects are ever properly closed, so your program leaks I/O resources with each call to readLineFromStdIn().

    The solution is to use a single shared BufferedReader object for each invocation of readLineFromStdIn().

    0 讨论(0)
提交回复
热议问题