1

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?

2 Answers2

4

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

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.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • 3
    It says [here](http://stackoverflow.com/questions/1388602/do-i-need-to-close-both-filereader-and-bufferedreader?rq=1) that closing the BufferedReader would close the InputStreamReader as well. – user2789772 Jan 30 '14 at 05:21
  • Indeed it does. 1) You should only close the outside decorator of this type, here the BufferedReader. 2) Surely you're not recommending that catch blocks be ignored, are you? 3) I usually check for null before closing. Please remember that newbies will take your code literally, including empty catch blocks. – Hovercraft Full Of Eels Jan 30 '14 at 05:24
  • @HovercraftFullOfEels : It should be handle Question owner as per his requirement. – Abimaran Kugathasan Jan 30 '14 at 05:26