Java 自动资源管理

从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

原有拷贝文件代码一般都是在finally中关闭。

public void copyFile(String fileInput, String fileOutput) {
    InputStream input = null;
    OutputStream output = null;
    try {
        input = new FileInputStream(fileInput);
        output = new FileOutputStream(fileOutput);

        byte[] byteArray = new byte[1024];
        int len = 0;
        while((len = input.read(byteArray)) != -1) {
            output.write(byteArray, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用 try-with-resources 语句来简化代码。

public void copyFile(String fileInput, String fileOutput) {		 
    try (InputStream input = new FileInputStream(fileInput);
            OutputStream output = new FileOutputStream(fileOutput)) {
        byte[] byteArray = new byte[1024];
        int len = 0;
        while((len = input.read(byteArray)) != -1) {
            output.write(byteArray, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

资源会在try代码后自动关闭,原因就在于它们都实现了AutoCloseable接口。

Resource实现AutoCloseable接口,并拥有open()方法

public class Resource implements AutoCloseable {

    public void open(int value) throws IOException {
        if (value == 1) {
            throw new IOException();
        }
    }

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

}

调用open(int)方法,第一次没有异常发生,正常关闭。第二次发生异常,捕获异常后正常关闭。

public static void main(String[] args) {
    try (Resource resource = new Resource()) {
        resource.open(0);
    } catch (IOException e) {
        System.out.println("catch IOException");
    }

    try (Resource resource = new Resource()) {
        resource.open(1);
    } catch (IOException e) {
        System.out.println("catch IOException");
    }
}

输出

Auto close
catch IOException
Auto close
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值