码迷,mamicode.com
首页 > 编程语言 > 详细

Java异常关闭资源的两种方式

时间:2018-06-09 18:52:32      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:tno   resources   tput   lan   new   style   utils   资源   try   

try-catch-finally 常用,在异常关闭时应判断流是否为空

public class CloseableUtils {
    public static void closeable(Closeable ... closeIO) {
        for(Closeable clo:closeIO) {
            if(clo!=null) {
                try {
                    clo.close();
                } catch (IOException e) {
                    System.out.println(DateUtils.getNowTime()+clo.getClass().getName()+"关闭发生异常"+e);
                }
            }
        }
    }
}

 

try-with-resources  ,它会自动关闭括号内的资源(resources),不用手动添加代码  


注意:
1. resource 必须继承自 java.lang.AutoCloseable 2. 定义和赋值必须都在try里完成
try (FileOutputStream f = null;) {
    f = new FileOutputStream(new File(""));
    } catch (IOException e) {
        e.printStackTrace();
}

Java异常关闭资源的两种方式

标签:tno   resources   tput   lan   new   style   utils   资源   try   

原文地址:https://www.cnblogs.com/dc-earl/p/9160307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!