Possible Duplicate:
“using” keyword in java
I'm transitioning from C# to java, so please bear with me...
When reading a file in C#, you simply wrap it all in a big 'using' block, so that if you have an exception, the file will still be closed. Like so (maybe inaccurate but you get the idea):
using(FileStream fs = new FileStream("c:\\myfile.txt")) {
// Any exceptions while reading the file here won't leave the file open
}
Is there a convenient equivalent in java 5 or 6? I get the impression that lately java has been 'borrowing' some of the syntactic sugar from c# (such as foreach) and so i wouldn't be surprised if there's a java equivalent of using these days.
Or do i just have to use a try..finally block? 'Using' is just so much nicer i think...
There's no equivalent syntax sugar using statements in Java 5 or 6. However, a proposal for automatic resource management which adds a familiar Disposable interface seems to have been accepted for Java 7 . Until then, you have to manually code a try...finally.