Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare and close InputSteam?

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 ?

like image 470
comatose Avatar asked Dec 05 '22 16:12

comatose


1 Answers

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);
}
like image 106
JB Nizet Avatar answered Dec 17 '22 00:12

JB Nizet