Java TWR 语法 Try With Resource

更多 Java 基础知识方面的文章,请参见文集《Java 基础知识》


resource

A resource is an object that must be closed after the program is finished with it.
resource 是一个对象,需要在程序结束前将其关闭。

Java7 之前,如何关闭资源

使用 finally 来确保资源会被关闭。

例如:

public static void main(String[] args) throws Exception {
    InputStream bin = new BufferedInputStream(new FileInputStream("a.txt"));
    try {
        int c;
        while ((c = bin.read()) != -1) {
            System.out.print((char) c);
        }
    } finally {
        bin.close();
    }
}

Java7 开始提供 TWR 语法 Try With Resource

The try-with-resources statement ensures that each resource is closed at the end of the statement.
TWR 语法确保了资源会被自动释放。
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable
, can be used as a resource.
资源的类需要实现 AutoCloseable 接口。

例如 BufferedInputStream,它的父类 InputStream 实现了 Closeable 接口:

public abstract class InputStream implements Closeable

The Closeable interface extends the AutoCloseable interface.

因此可以通过如下方式使用 BufferedInputStream
无论是否出现 Exception,bin 都会在 Try 语句块结束时自动释放。

public static void main(String[] args) throws Exception {
    try (InputStream bin = new BufferedInputStream(new FileInputStream("a.txt"))) {
        int c;
        while ((c = bin.read()) != -1) {
            System.out.print((char) c);
        }
    }
}

你可能感兴趣的:(Java TWR 语法 Try With Resource)