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;
    在这里插入图片描述

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    10 款最佳剪贴板管理器
    悉数美剧《黑客军团》中的黑客工具
    Vim的使用方法
    Mysql跨平台(Windows,Linux,Mac)使用与安装
    Linux下网络故障诊断
    RHEL6.2下挂载光驱安装软件
    MySQL数据库服务器的架设
    Unix如何轻松快速复制
    【Linux基础】Linux常用命令汇总
    博客编号数字密码
  • 原文地址:https://www.cnblogs.com/javayida/p/13346734.html
Copyright © 2011-2022 走看看