F
F
ForsakenHedgehog2020-02-18 18:26:56
Java
ForsakenHedgehog, 2020-02-18 18:26:56

Do I need to close the I/O stream or does it close automatically?

The examples below read a string from the keyboard in two slightly different ways.

String file = new BufferedReader(new InputStreamReader(System.in)).readLine();


BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String file = reader.readLine();
reader.close();


In the first case, as I understand it, manually I cannot close the input stream. Does it close automatically or does it exist until the program terminates?

And tell me for the future, what is the name of such a syntactic construction for creating an instance of a class, as in the first example? One of those cases when you do not know how to formulate a question in Google.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
melouw, 2020-02-21
@ForsakenHedgehog

It is recommended to use try-with-resources

try (BufferedReader reader =
                     new BufferedReader(new InputStreamReader(System.in))) {
            String file = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

In this case, the resources are released correctly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question