解决try catch finally中close的问题

解决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接口。

你可能感兴趣的:(JAVA)