Java 等价于 C#'using' 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3295464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:11:01  来源:igfitidea点击:

Java equivalent of C# 'using' statement

c#javafileexceptionusing

提问by Chris

Possible Duplicate:
“using” keyword in java

可能的重复:
Java 中的“使用”关键字

I'm transitioning from C# to java, so please bear with me...

我正在从 C# 过渡到 Java,所以请耐心等待...

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):

在 C# 中读取文件时,您只需将其全部包装在一个大的“using”块中,这样如果出现异常,该文件仍将被关闭。像这样(可能不准确,但你明白了):

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.

java 5 或 6 中是否有方便的等价物?我的印象是,最近 java 一直在从 c# 中“借用”一些语法糖(例如 foreach),所以如果现在有一个相当于使用的 java,我不会感到惊讶。

Or do i just have to use a try..finally block? 'Using' is just so much nicer i think...

还是我只需要使用 try..finally 块?我认为“使用”要好得多......

回答by Trillian

There's no equivalent syntax sugar using statements in Java 5 or 6. However, a proposalfor automatic resource management which adds a familiar Disposable interface seems to have been acceptedfor Java 7 . Until then, you have to manually code a try...finally.

在 Java 5 或 6 中没有使用语句的等效语法糖。但是,添加熟悉的 Disposable 接口的自动资源管理提案似乎已被Java 7接受。在此之前,您必须手动编写代码尝试……最后。

回答by Nulldevice

Have to use try .. finally

必须使用try .. 最后

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

PS foreach(对集合进行迭代)不是 C# 的发明