Java – 如何使用Try with Resources

Java – try catch finally 与 Try with Resources

概述

从Java7开始就已经支持 try-with-resources了,我们可以在try的代码块中声明这些资源会在代码执行完毕后将确保关闭。这资源类必须要声明实现AutoCloseable接口。

使用try-with-resouces

很简单,为了能自动关闭资源,资源声明和初始化必须在try中。例如:

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

用 try-with-resources 替换 try–catch-finally

显而易见,一个传统典型的try-catch-finally的代码块要冗长的多

        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("text.txt"))) {
            while (scanner.hasNext()) {
                System.out.println(scanner.nextLine());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

try-with-resources 应用于多个资源 Resource

将多个资源的声明语句在try()的代码块里即可。

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

如何实现自定义资源的自动关闭

先看下Scanner类是如何处理资源关闭的:

public final class Scanner implements Iterator, Closeable {

    // Internal buffer used to hold input
    private CharBuffer buf;
    ...

构建一个自定义资源需要实现Closeable 或者 AutoCloseable接口,覆写其close方法。

public class MyResource implements AutoCloseable{
    @Override
    public void close() throws Exception {
        // TODO Auto-generated method stub
        
    }
}

多个资源的关闭顺序是怎样的?

写个代码测试下:
Resouce1

public class MyResource1 implements AutoCloseable {
    
    public MyResource1() {
        super();
        System.out.println("Constructor : MyResource1 ");
    }

    public void dosth(){
        System.out.println("Do sth : MyResouce1");
    }
    
    @Override
    public void close() throws Exception {
        System.out.println("Close : MyResouce1");
    }

}

Resource2:

public class MyResource2 implements AutoCloseable {

    public MyResource2() {
        super();
        System.out.println("Constructor : MyResouce2");
    }
    
    public void dosth(){
        System.out.println("Do sth: MyResouce2");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Close : MyResouce2");
    }

}

main方法:

    public static void main(String[] args) {
        try (MyResource1 myResource1 = new MyResource1();
                MyResource2 myResource2 = new MyResource2()) {
            myResource1.dosth();
            myResource2.dosth();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

运行输出:

Constructor : MyResource1
Constructor : MyResouce2
Do sth : MyResouce1
Do sth: MyResouce2
Close : MyResouce2
Close : MyResouce1

由此可见,最先声明定义打开的将最后关闭。

try catch finally 可以在其代码块中 继续使用

结语

文章介绍了 Try with Resources 的使用,如何实现自定义资源自动关闭,多个资源打开后的关闭顺序。就此能少写好些行代码。

Github

你可能感兴趣的:(Java – 如何使用Try with Resources)