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(); } } |
1 answer
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(); |
Почему?- because when closingBufferedReaderall nested streams are automatically closed. - post_zeew