I\'ve seen reference in some C# posted questions to a \"using\" clause. Does java have the equivalent?
Yes, since Java 7 you can rewrite:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
As
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
The objects passed as parameters to the try statement should implement java.lang.AutoCloseable
.Have a look at the official docs.
For older versions of Java checkout this answer and this answer.