user2789772
user2789772

Reputation: 51

Closing a BufferedReader

If I invoke a BufferedReader the following way:

Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());

Will the JVM know to automatically close it when not in use? If not, how do I go about closing it?

Upvotes: 1

Views: 679

Answers (2)

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

Don't chain them, declare and assign variables, then close it after the usage.

InputStreamReader isReader;
BufferedReader bfReader;
try {
     isReader = new InputStreamReader(System.in);
     bfReader = new BufferedReader(isReader).readLine();
} catch (Exception e) {
// handle as per the requirement.
} finally {
    bfReader.close();
}

If you use java 7, then, if you defined withing the try clause, then those will auto closable. Check here for more details

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

If you are using java 7 or greater and your code is in try catch resource block, then it is Auto closes.

If in below versions you have to close with close(). For that you have to change your current way of using and get the reference.

Upvotes: 4

Related Questions