try-with-resources

传统的try-catch、try-catch-finally、try-finally用法,这里就不再一一介绍了。可详见《程序员成长笔记(一)》。
笔者语录:哈哈,上面这句话是对本人自己说的,因为此笔记我不会分享在网上。

JDK1.7开始,官方就给我们提供了自动关闭资源的方式。

传统的,关闭资源的方式形如:

package com;

import java.io.*;

/**
 * JDK1.7新特性之 try-with-resources测试
 *
 * @author JustryDeng
 * @date 2018/10/27 13:30
 */
public class TryWithResourcesTest {

    /** 要读入的文件 */
    private static final String filePath = "C:/Users/JustryDeng/Desktop/hello.txt";

    /** 要写出的文件 */
    private static final String destPath = "C:/Users/JustryDeng/Desktop/hi.txt";

    /**
     * 传统的try-catch-finally
     *
     * @date 2018/10/30 11:18
     */
    public static void main(String[] args) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 输入流 读取文件
            is = new FileInputStream(filePath);
            StringBuilder sb = new StringBuilder();
            int a;
            while ((a = is.read()) >= 0) {
                sb.append((char) a);
            }
            String result = new String(sb.toString().getBytes("ISO-8859-1"), "utf-8");
            System.out.print(result);
            // 输出流 写出文件
            os = new FileOutputStream(destPath);
            os.write(result.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

提示:FileOutputStream是指向内存的流(了理解为:虚拟的流),GC机制会自动回收,无需关闭。

 

try-with-resources的方式形如:

package com;

import java.io.*;

/**
 * JDK1.7新特性之 try-with-resources测试
 *
 * @author JustryDeng
 * @date 2018/10/27 13:30
 */
public class TryWithResourcesTest {

    /** 要读入的文件 */
    private static final String filePath = "C:/Users/JustryDeng/Desktop/hello.txt";

    /** 要写出的文件 */
    private static final String destPath = "C:/Users/JustryDeng/Desktop/hi.txt";

    /**
     * 新特性try-with-resources
     *
     * @date 2018/10/30 11:18
     */
    public static void main(String[] args) {
        try (
                // 输入流
                InputStream is = new FileInputStream(filePath);
                // 输出流
                OutputStream os = new FileOutputStream(destPath)
        ) {
            StringBuilder sb = new StringBuilder();
            int a;
            while ((a = is.read()) >= 0) {
                sb.append((char) a);
            }
            String result = new String(sb.toString().getBytes("ISO-8859-1"), "utf-8");
            System.out.print(result);
            os.write(result.getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我们把上面的try-with-resource对应的.class文件反编译一下,是这样的:

提示:FileOutputStream是指向内存的流(了理解为:虚拟的流),GC机制会自动回收,无需关闭。

 

直接给出结论:

结论一:只有(直接或间接)实现了AutoCloseable接口的类,才能作为try-with-resources中的resources,放在try后面
             的括号里。实现了继承了改接口的接口、实现了该接口的类有:

结论二:一般的,try-with-resources自动释放资源的顺序为:越后创建的资源,越先释放。

结论三:try-with-resources实际上还是在finally块中释放资源的,只不过此步骤不再需要程序员们主动写代码来释放了,
            编译器在编译时会自动帮我们完成。

结论四:照本文上面的try-catch-finally的示例,如果在catch中抛出了异常A,同时又在finally中关闭释放资源时,(由于各
            种原因)又抛出了异常B,那么最终抛出给程序员的将会是异常B(因为只能抛出一个异常),再排查原因时,这将
            会给程序员们带来很大的麻烦。而使用try-with-resources的话,那么出现此情况时,最终抛出给程序员的异常将
            会是异常A(异常B被抑制了,我们可以使用.getSuppressed()方法来获取被抑制的异常)。
注:此处结论本人并没有给出示例演示,感兴趣的可以参考https://www.jianshu.com/p/3ab87269140c

结论五:虽然我们使用try-catch-finally时,也可以按照类似上图中的写法来使最终抛出的异常是catch中的异常,但无疑
             会麻烦会多,程序可读性也差,建议使用try-with-resources方式。

结论六:try-with-resources除了支持try(){}catch{}try(){}finally{}try(){} catch{}finally{}搭配外,还额外支
            持try(){}

 

^_^ 如有不当之处,欢迎指正

^_^ 参考链接
           https://blog.csdn.net/u012668925/article/details/53941471
           https://www.jianshu.com/p/3ab87269140c

^_^ 本文已经被收录进《程序员成长笔记(三)》,笔者JustryDeng

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值