您的位置:首页 > 其它

解决try catch finally中close的问题

2016-07-21 15:07 302 查看

解决try catch finally中close的问题

一直觉得要在finally里关闭流,是很讨厌的,因为代码会非常糟糕。然后在SO中看到了一个JDK7+的方法:

try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}


The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

只有实现了AutoClosable接口,才可以被当作一个资源使用。从反编译来看,的确实现了AutoClosable接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: