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();
}

 
                    
            
                

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-18
  • 2022-12-23
  • 2021-12-13
猜你喜欢
  • 2021-12-19
  • 2021-04-14
  • 2022-01-17
  • 2021-09-20
  • 2021-07-13
  • 2021-07-22
相关资源
相似解决方案