What happens to a BufferedReader that doesn't get closed within a callable.call?

后端 未结 5 820
后悔当初
后悔当初 2021-02-04 14:47

I have three questions.

To explain, I was reviewing someone\'s code, and noticed BufferedReaders sometimes aren\'t being closed. Usually, Eclipse gives a w

5条回答
  •  我寻月下人不归
    2021-02-04 15:37

    No matter where you open the stream you should close it in the finally block and it is a good practice to test the stream for null as well, because if the file is not existing the stream will be null, exception will be thrown (FileNotFoundException) but the finally bock is done. I.e. the content of the call method should be:

       BufferedReader stdOut = null;
       String output = null;
            try {
                stdOut = new BufferedReader(new InputStreamReader(stream));
                while ((output = stdOut.readLine()) != null) {
                    log.info("[" + prepend + "] " + output);
                }
            } catch (FileNotFoundException ex) {
                log.warn("Unable to open nonexisten file " + whichOne);  
            } catch (IOException ex) {
                log.warn("Unable to read from stream");  
            } finally {
                if (stdOut != null) {
                    try {
                       stdOut.close();
                    } catch (IOException e) {
                        log.warn("Unable to close the stream");
                    }
                }
            }
            return 0;
    

    Or if you are allowed to use Java 7 you can use the benefits of AutoCloseable interface and the new language structure for this purpose. see http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html

提交回复
热议问题