15

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...

Community
  • 1
  • 1
Chris
  • 39,719
  • 45
  • 189
  • 235
  • 5
    If you claim that a question is duplicate, it would be helpful if you provide a link to the question it is supposed to duplicate. Just marking things as duplicate is not helpful at all and makes this site less useful. This question is a good example of why you must provide a link: when I click on the tag "using", I get 568 hits -- next to impossible to find the original answer in such a long list. If I search for [using] [java] I still get 24 hits and the answer I am looking for is on the *second* page of the list of results: http://stackoverflow.com/questions/2943542/using-keyword-in-java – Berend Engelbrecht Mar 21 '13 at 09:41

2 Answers2

22

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Trillian
  • 6,207
  • 1
  • 26
  • 36
2

Have to use try .. finally

P.S. foreach (iteration over a collection) is not an invention of C#

Nulldevice
  • 3,926
  • 3
  • 31
  • 37