我已经看到在一些C#发布的问题中引用了一个"using"子句.java有相同的功能吗?
是.Java 1.7引入了try-with-resources构造,允许您编写:
try(InputStream is1 = new FileInputStream("/tmp/foo"); InputStream is2 = new FileInputStream("/tmp/bar")) { /* do stuff with is1 and is2 */ }
......就像一个 using
声明.
不幸的是,在Java 1.7之前,Java程序员被迫最终使用try {...} {...}.在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(); }
是的,因为Java 7你可以重写:
InputStream is1 = new FileInputStream("/tmp/foo"); try{ InputStream is2 = new FileInputStream("/tmp/bar"); try{ /* do stuff with is1 and is2 */ } finally { is2.close(); } } finally { is1.close(); }
如
try(InputStream is1 = new FileInputStream("/tmp/foo"); InputStream is2 = new FileInputStream("/tmp/bar")) { /* do stuff with is1 and is2 */ }
作为参数传递给try语句的对象应该实现java.lang.AutoCloseable
.看一下官方文档.
对于旧版本的Java,请查看此答案和此答案.
语言中最接近的等价物是使用try-finally.
using (InputStream in as FileInputStream("myfile")) { ... use in ... }
变
final InputStream in = FileInputStream("myfile"); try { ... use in ... } finally { in.close(); }
请注意,一般形式总是:
acquire; try { use; } finally { release; }
如果获取在try块内,则在采集失败的情况下将释放.在某些情况下,您可能会遇到不必要的代码(通常在上面的示例中测试null),但是在ReentrantLock的情况下,会发生坏事.
如果你经常做同样的事情,你可以使用"执行"这个习惯用法.不幸的是,Java的语法很冗长,所以有很多更大胆的板块.
fileInput("myfile", new FileInput() { public Void read(InputStream in) throws IOException { ... use in ... return null; } });
哪里
public staticT fileInput(FileInput handler) throws IOException { final InputStream in = FileInputStream("myfile"); try { handler.read(in); } finally { in.close(); } }
更复杂的例子我,例如,换行异常.