Prefer try-with-resources to try-finally

Demo1(Read the second line)
finally和try里如果同时抛出异常,try里面的异常不会显示在异常堆栈里,会影响debug。

static void readFirstLineOfFile(String path) throws IOException {
        BufferedReader bufferedReader
                = new BufferedReader(new FileReader(path));
        try{
            bufferedReader.readLine();
            System.out.println(bufferedReader.readLine());
        }finally {
            bufferedReader.close();
        }
    }

Demo2(Copy)
需要关闭的资源多了,用try-with有点傻

static void copy(String src, String dst) throws IOException {
        FileInputStream in = new FileInputStream(src);
        try{
            FileOutputStream out = new FileOutputStream(dst);
            try{
                byte[] b = new byte[100];
                int n = 0;
                while( 0<=(n = in.read(b))){
                    out.write(b, 0, n);
                }
            }finally{
                out.close();
            }
        }finally {
            in.close();
        }
    }

Demo3(New-Read the second line)
使用try-resources会自动执行close方法,这样可读性更高。AutoCloseable接口需要被实现。

static void readFirstLineOfFileNew(String path) throws IOException {
        try(BufferedReader bufferedReader
                    = new BufferedReader(new FileReader(path))){
            bufferedReader.readLine();
            System.out.println(bufferedReader.readLine());
        }
    }

Demo4
使用了try-with-resources

static void copy2(String src, String dst) throws IOException {
        try(FileInputStream in = new FileInputStream(src);
            FileOutputStream out = new FileOutputStream(dst);
        ) {
            byte[] b = new byte[100];
            int n = 0;
            while( 0<=(n = in.read(b))){
                out.write(b, 0, n);
            }
        }
    }

test unit

    public static void main(String[] args) throws IOException {
//        Item9.readFirstLineOfFile("c:/work/a.txt");
//        Item9.copy("c:/work/a.txt", "c:/work/b.txt");
//        Item9.readFirstLineOfFileNew("c:/work/a.txt");
        Item9.copy2("c:/work/a.txt", "c:/work/c1.txt");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值