zoukankan      html  css  js  c++  java
  • Java小知识--IO流中--try-catch-resource的一个小发现

    在用到 IO 流时 经常会try catch异常,当我catch住异常时,如果用的是   

           try( 读/写的资源   ) {

                   代码块

                     } catch( IOException e )  {

                          e.printStackTrace();

                                    }  

      时,jdk会替我自动释放掉资源 ,不用再写   .close()了。

      但当读/写资源时,如果用的构造方法是 参数为File类型  时,需要把  新建path对象的 那条语句写在 try()上面,不然会报错。

      例子:

    public static void method1(){
            File path1 = new File("E:\IOTest\1.txt");     //当参数为File类型 时,这句话 要写在try()外面。
            try(
                InputStream in2 = new FileInputStream(path1);//参数为File类型的构造方法
                    ){
     
                int b = 0;
              
                while((b = in2.read()) != -1) {
                    System.out.println(b);
                }

            } catch (IOException e) {

                e.printStackTrace();
            }
        }

  • 相关阅读:
    TCP的三次握手与四次挥手
    关系型数据库和非关系型数据库的区别
    wedpack打包的基本使用
    express的中间件与next()
    react-redux (react)
    判断数据类型的几种方式
    关于NODE__APP在windows系统解决适配问题
    中间件,前后端分离思想
    移动端
    EasyUI combobox 动态下拉列表
  • 原文地址:https://www.cnblogs.com/raphaelJava-4560/p/12976703.html
Copyright © 2011-2022 走看看