Java7技术系列:try-with-resource

Java7技术系列:try-with-resource
Java7技术系列:int与二进制的转换优化
Java7技术系列:MultiCatchException
Java7技术系列:NIO.2异步IO
Java7技术系列:DI依赖注入
Java7技术系列:Queue
Java7技术系列:Java并发

/**
 * Java7以前对IO流的处理除了语法复杂,即使使用了try catch但仍有可能流并没有正常关闭
 */
private static void tryCatchBeforeJava7(String targetUrl) {
    InputStream is = null;
    OutputStream os = null;
    try {
        File file = new File(targetUrl);
        URL url = new URL("");
        is = url.openStream();
        os = new FileOutputStream(file);
        byte[] buf = new byte[4096];
        int len;
        while ((len = is.read(buf)) >= 0) {
            os.write(buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 让Java7自己关闭流,能避免认为疏漏或错误
 *
 * try-with-resource能自动关闭实现了AutoCloseable或Closeable接口的资源
 * 在执行的语句抛出异常时,流的关闭会根据代码声明流相反的顺序关闭
 *
 * try-with-resource也可以有catch和finally语句,在try-with-resource抛出异常后,会再调用finally语句
 */
private static void tryWithResource(String targetUrl) throws MalformedURLException {
    File file = new File(targetUrl);
    URL url = new URL("");
    try (InputStream is = url.openStream();
         OutputStream os = new FileOutputStream(file)) {
        byte[] buf = new byte[4096];
        int len;
        while ((len = is.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * 使用try-with-resource特性时还是要小心,因为在某些情况下资源可能无法关闭。
 * 比如下面的代码,如果文件somFile.bin创建ObjectInputStream时出错,FIleInputStream可能就无法正确关闭
 *
 * 为避免该问题,每一个资源都应该独立声明
 */
private static void tryWithResourceAttention() {
    // 创建ObjectInputStream时如果出错,将导致FileInputStream无法正确关闭
    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("someFile.bin"))) {

    }

    // 每个资源独立声明,防止某些资源无法正常关闭
    try (FileInputStream is = new FileInputStream("someFile.bin");
            ObjectInputStream in = new ObjectInputStream(is)) {

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值