Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of C# 'using' statement [duplicate]

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

like image 568
Chris Avatar asked Jul 21 '10 00:07

Chris


People also ask

Is Java similar to C?

C is a middle-level language as it binds the bridges between machine-level and high-level languages. Java is a high-level language as the translation of Java code takes place into machine language, using a compiler or interpreter. C is only compiled and not interpreted. Java is both compiled and interpreted.

Is Java built on C?

The very first Java compiler was developed by Sun Microsystems and was written in C using some libraries from C++. Today, the Java compiler is written in Java, while the JRE is written in C.

Is Java similar to C or C++?

As Java was inspired by C and C++, its syntax is similar to these languages. C++ is both a procedural and object-oriented programing language. Hence, C++ has features specific to procedural languages as well as features of object-oriented programming language. Java is a completely object-oriented programming language.

Which is more efficient Java or C?

C is normally faster than Java, if it is written efficiently, but it always depends on the compiler. Some compilers support optimization on the compile time, to produce more efficient code, by removing redundant code and other unnecessary artefacts.


2 Answers

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.

like image 146
Trillian Avatar answered Oct 14 '22 02:10

Trillian


Have to use try .. finally

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

like image 33
Nulldevice Avatar answered Oct 14 '22 04:10

Nulldevice