0

Following is a method which takes input from user and returns the response.

private String getValueFromUser(String propertyValue){
    String response = ""; 
    try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
        response = br.readLine();
        if (response.equals("")){
            return propertyValue;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

This method when executed runs fine for first call but throws the following exception in the subsequent calls.

java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
at java.io.BufferedInputStream.read(BufferedInputStream.java:336)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.ripple.utility.ConfigurationUtility.getValueFromUser(ConfigurationUtility.java:119)
at com.ripple.utility.ConfigurationUtility.createPropertiesDTO(ConfigurationUtility.java:108)
at com.ripple.utility.ConfigurationUtility.setProperties(ConfigurationUtility.java:169)
at com.ripple.utility.ConfigurationUtility.main(ConfigurationUtility.java:191)

Can someone please help in explaining the problem with the code ?

udit
  • 101
  • 3
  • 17
  • You don't need to close the System.in but you do need to retain a buffer as it could read as much data as is available not just the minimum you need right now. – Peter Lawrey Jul 18 '18 at 06:47

1 Answers1

3

When the BufferedReader gets closed at the end of the try-with-resources block, System.in is also closed and it can't be reopened.

You should open the reader once and keep it open somewhere where you can use it until your program is finished.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • @ShubhenduPramanik because you ran it only once? – Kayaman Jul 18 '18 at 06:05
  • Creating buffered reader like the one shown below worked: try(BufferedReader br = new BufferedReader(new InputStreamReader(new NoCloseInputStream(System.in)))){} – udit Jul 23 '18 at 03:21