说说Java7 之 Try with Resources

说说Java7 之 Try with Resources

java7引入Try with Resources语法,允许我们在try块中声明并使用资源,确保在使用之后资源被关闭。资源必须实现AuthCloseable接口。

使用Try with Resources

简单地说,为了自动关闭,资源必须在try块中声明并初始化,示例如下:

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
}

使用Try with Resources 代替 try–catch-finally

上面方式非常简洁,因此建议使用Try with Resources 代替传统的冗长方式:try–catch-finally。
下面通过示例比较两种方式,首先是采用try–catch-finally,然后采用新的方法,通过Try with Resources实现等价功能:

Scanner scanner = null;
try {
    scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}

然后,使用Try with Resources实现超级简洁的解决方案:

try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}

try-with-resources 与多个资源

可以在try-with-resources 块中声明多个资源,通过分号分割:

try (Scanner scanner = new Scanner(new File("testRead.txt"));
    PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
    while (scanner.hasNext()) {
    writer.print(scanner.nextLine());
    }
}

使用AutoCloseable接口自定义资源

为了创建自定义可被 try-with-resources块自动处理的资源,则该类需要实现Closeable 或 AutoCloseable 接口,然后重载其close方法:

public class MyResource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("Closed MyResource");
    }
}

关闭资源顺序

最先定义的资源最后被关闭,请看示例:

第一个资源:

public class AutoCloseableResourcesFirst implements AutoCloseable {

    public AutoCloseableResourcesFirst() {
        System.out.println("Constructor -> AutoCloseableResources_First");
    }

    public void doSomething() {
        System.out.println("Something -> AutoCloseableResources_First");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Closed AutoCloseableResources_First");
    }
}

第二个资源:

public class AutoCloseableResourcesSecond implements AutoCloseable {

    public AutoCloseableResourcesSecond() {
        System.out.println("Constructor -> AutoCloseableResources_Second");
    }

    public void doSomething() {
        System.out.println("Something -> AutoCloseableResources_Second");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Closed AutoCloseableResources_Second");
    }
}

调用代码:

private void orderOfClosingResources() throws Exception {
    try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
        AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {

        af.doSomething();
        as.doSomething();
    }
}

输出结果:

Constructor -> AutoCloseableResources_First
Constructor -> AutoCloseableResources_Second
Something -> AutoCloseableResources_First
Something -> AutoCloseableResources_Second
Closed AutoCloseableResources_Second
Closed AutoCloseableResources_First

catch 和 finally

使用try-with-resources块,仍可以有catch 和 finally,它们功能和传统的try块一样。

总结

本文我们讨论了如何使用try-with-resources,通过示例说明如何使用try-with-resources代替try, catch 和 finally。使用AutoCloseable 接口自定义资源以及资源关闭顺序。

你可能感兴趣的:(java8~9核心功能)