readline() returns null in Java

后端 未结 2 1936
-上瘾入骨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: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().

提交回复
热议问题