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
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