try-with-resources

try-with-resources

JDK7新增的处理方式,是为资源关闭设置的语法
try(需要关闭的资源对象(任何实现java.lang.AutoClosable或java.io.Closable的对象)
{
可能发生异常的逻辑代码
}
catch(异常类型 e)
{
异常处理代码
}
catch(异常类型 e)
{
异常处理代码
}
关闭资源和final的执行顺序:在try-with-resource语句中,任何catch或finally块在声明的资源关闭后运行
Java中需要调用close()方法手动关闭的资源:类似于InputStream,OutputStream,Scanner,PrintWtiter的资源,一般通过try-catch-finally实现,例如:

public class K
{
    public static void main(String[] args)
    {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try
        {
            fileInputStream = new FileInputStream("src/a.txt");
            fileOutputStream = new FileOutputStream("src/b.txt");
            byte[] bytes = new byte[1024];
            int b;
            while(-1!=(b=fileInputStream.read(bytes)))
            {
                fileOutputStream.write(bytes);
            }
            fileOutputStream.flush();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}


用try-with-resources代替

public class J
{
    public static void main(String[] args)
    {
        try(FileInputStream fileInputStream = new FileInputStream("src/a.txt");
            FileOutputStream fileOutputStream = new FileOutputStream("src/b.txt")
        )
        {
           byte[] b = new byte[1024];
           int i;
            while(-1!=(i=fileInputStream.read(b)))
            {
                fileOutputStream.write(b);
            }
            fileOutputStream.flush();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

面对必须要关闭的资源,我们总是应该优先用try-with-resources,而不是try-catch-finally,其产生的代码更简短,更清晰,产生的异常对我们更有用,try-with-resources语句让我们更容易编写必须要关闭的资源的代码,若采用try-finally基本做不到这点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值