Java 7中的Try-with-resources

java 传统IO处理特别麻烦,Try-with-resources是java7中一个新的异常处理机制,它能够很容易地关闭在try-catch语句块中使用的资源。

旧代码风格

public static void main(String[] args) {
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream("data.txt");
        int data;
        while ((data = inputStream.read()) != -1) {
            System.out.print((char) data);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

我们看到,需要在finally手动关闭流,关闭还可能抛异常,又得处理,非常繁杂。

java7 风格

public static void main(String[] args) {
    try (InputStream inputStream = new FileInputStream("data.txt")){
        int data;
        while ((data = inputStream.read()) != -1) {
            System.out.print((char) data);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

当try语句块运行结束时,FileInputStream 会被自动关闭。这是因为FileInputStream 实现了java中的java.lang.AutoCloseable接口。所有实现了这个接口的类都可以在try-with-resources结构中使用。

如果有多个资源,按顺序声明,使用;分开:

public static void main(String[] args) {
    try (InputStream inputStream = new FileInputStream("data.txt");
         BufferedInputStream bis = new BufferedInputStream(inputStream)) {
        int data;
        while ((data = inputStream.read()) != -1) {
            System.out.print((char) data);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

AutoClosable 上面提到,FileInputStream实现了AutoClosable接口,可以自定义,如下:

public class Test {

    public static void main(String[] args) {
        try (TestAutoClose test = new TestAutoClose()) {
            test.doSomething();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class TestAutoClose implements AutoCloseable {
    public void doSomething() {
        System.out.println("do something");
    }

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

do something TestAutoClose close


参考文档:Try-with-resources in Java 7

CONTENTS