public static void main(String[] args) { try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { System.out.println(reader.readLine()); System.out.println(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } // ========= try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { System.out.println(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } 
  • Why reuse? Why not use the first one? - Chubatiy
  • This is a simplified example so as not to embed all the code. In general, several different methods are used in different classes and this problem has arisen. - I. Maslennikov
  • one
    Почему? - because when closing BufferedReader all nested streams are automatically closed. - post_zeew
  • And you can read more? How correctly to use then in structure with several classes? - I. Maslennikov
  • And you are the object of the reader, that you pass on all the functions? - GenCloud

1 answer 1

The exception IOException generated because after the first use of the BufferedReader reader you immediately implicitly (with try-with-resources ) close it.

Closing the BufferedReader reader leads to the automatic closing of all threads invested in it, in particular, System.in . The System.in stream cannot be rediscovered , so the next time you use System.in you get the message that Stream closed .

If you need to use input stream in various classes, then, for example, you can make the BufferedReader instance a public static field of the Main class:

 public static BufferedReader sReader = new BufferedReader(new InputStreamReader(System.in)); 

and use it as:

 String s = Main.sReader.readLine(); 

But in this case, after the last entry, do not forget to close it:

 Main.sReader.close();