user3501758 user3501758 - 1 month ago 19
Java Question

close() closes input streams permanently

I am trying to make a simple method readIn() that reads something in from System.in. (Can't use Console because System.console() returns null when I run in Eclipse). The idea is to call readIn as needed, like this

classs Foo{
public static void(String[] arg){

String first = readIn("First, please");
System.out.println(first);

String second = readIn("Second, please");
System.out.println(second);
}
}


Here is the simplest form of readIn():

static String readIn(String prompt){

System.out.println(prompt + ": ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
br.close(); // PROBLEM STATEMENT
return line;

}


If I omit the br.close() statement it works fine - I can call readIn repeatedly. But if I close br, as I should, then only the first call works. Second call throws IOException: Stream closed. As expected, the same thing happens with try-with-resources in readIn:

static String readIn(String prompt){

System.out.println(prompt + ": ");
String line;
try(
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)) )
{
line = br.readLine();
}

return line;
}


Same thing happens with Scanner(System.in) instead of BufferedReader. It does not happen when reading from files.

Which stream is closed if a new BufferedReader or Scanner is made in every call to readIn? Is this something about close() closing the "underlying Readable/Closeable" (System.in)? Can it be reopened? Trying to understand, thanks.

Answer

br.close(); closes also system input stream System.in, so you can't use it unless you restart JVM. You can use the same BufferedReader instance for all required input from System.in

Don't be shy also to mix calls:

System.out.println
br.readLine();

They are related to different streams, so there shouldn't be any issues.