zoukankan      html  css  js  c++  java
  • try(){}的简单理解

    以前使用try catch-finally都是捕获异常,然后流关闭等等,代码总是这样的:好比往FileOutputStream写东西:

    @Test
      public void test2() throws IOException {
        File file = new File("E://test");
        if (!file.exists()) {
          file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        try {
          System.out.println("do something...");
          fileOutputStream.write("aaa".getBytes());
          fileOutputStream.flush();
        } catch (Exception e) {
          System.out.println("do ...");
        } finally {
          fileOutputStream.close();
        }
      }
    

    这样写很难受,可以进行优化,将FileOutputStream fileOutputStream = new FileOutputStream(file)放到try()里面,也可以放多个,

      @Test
      public void test2() throws IOException {
        File file = new File("E://test");
        if (!file.exists()) {
          file.createNewFile();
        }
       
        try( FileOutputStream fileOutputStream = new FileOutputStream(file);) {
          System.out.println("do something...");
          fileOutputStream.write("aaa".getBytes());
          fileOutputStream.flush();
        } catch (Exception e) {
          System.out.println("do ...");
        } 
      }
    

    try()里每个声明的变量类型都必须是Closeable的子类,就一个close方法;相当于系统自动将关闭操作放到了finally里面而不需要我们自己写了,很nice;
    在这里插入图片描述

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    WinDbg常用命令系列---线程相关操作~*
    WinDbg常用命令系列---?*
    使用WinDbg调试入门(内核模式)
    java基础-stringAPI
    springboot-集成WebSockets广播消息
    sprincloud-Feign配置二
    springcloud-Feign配置一
    springboot-集成jdbcTemplate
    spingboot2.x集成单元测试
    springboot跨域CORS处理
  • 原文地址:https://www.cnblogs.com/javayida/p/13346734.html
Copyright © 2011-2022 走看看