I\'ve seen reference in some C# posted questions to a \"using\" clause. Does java have the equivalent?
It was a long time coming but with Java 7 the try-with-resources statement was added, along with the AutoCloseable interface.
No, there is no using in Java, the most similar functionality is the "import" keyword.
Well, using was syntactic sugar anyway so Java fellows, don't sweat it.
Not that I'm aware of. You can somewhat simulate with a try...finally block, but it's still not quite the same.
Yes. Java 1.7 introduced the try-with-resources construct allowing you to write:
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
... just like a using
statement.
Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is 2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
The actual idiom used by most programmers for the first example is this:
InputStream is1 = null;
InputStream is2 = null;
try{
is1 = new FileInputStream("/tmp/bar");
is2 = new FileInputStream("/tmp/foo");
/* do stuff with is1 and is 2 */
} finally {
if (is1 != null) {
is1.close();
}
if (is2 != null) {
is2.close();
}
}
There is less indenting using this idiom, which becomes even more important when you have more then 2 resources to cleanup.
Also, you can add a catch clause to the structure that will deal with the new FileStream()'s throwing an exception if you need it to. In the first example you would have to have another enclosing try/catch block if you wanted to do this.