Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readline() returns null in Java

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 the input through the eclipse built-in console, everything goes well. But when using the Windows command line, the program prints:

Received '6'.  
Received 'null'.  
Invalid input. Terminating. (This line is written by another function that does an Integer.parseint()).  

My code is:

static String readLineFromStdIn(){  
try{  
        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));  
        String input = new String();  
        input = stdin.readLine();  
        System.out.println("Received '" + input + "'");  
        return(input);  
    }catch (java.io.IOException e) {  
        System.out.println(e);   
    }  
    return "This should not have happened";  
}  

Any clues?

like image 878
user1259401 Avatar asked Mar 09 '26 13:03

user1259401


1 Answers

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().

like image 97
user268396 Avatar answered Mar 12 '26 02:03

user268396