which of the following is the preferred way to close and declare the inputStream.
InputStream is = null;
String md5;
try{
is = new FileInputStream(FILE.getAbsoluteFile());
md5 = UTILS.getMD5Info(is);
} finally{
if(is != null)
is.close();
}
or
InputStream is = new FileInputStream(FILE.getAbsoluteFile());
String md5;
try{
md5 = UTILS.getMD5Info(is);
} finally{
is.close();
}
I don't see much difference between the two, but the 2nd way looks better as its a bit short. Is there any use of initializing the input stream inside a try block if we are not going to catch the exception and are just interested in garbage collecting the inputStream ?
If IOException was caught between the try and the finally, the first one would also handle the case where the constructor of the FileInputStream throws an IOException, whereas the second one would not. They wouldn't do the same thing. As is, the second one is cleaner.
Since Java 7, the best way is to use the try-with-resources statement:
try (InputStream is = new FileInputStream(FILE.getAbsoluteFile())) {
md5 = UTILS.getMD5Info(is);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With