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

  • 相关阅读:
    sl学习
    xc笔记
    1_2_3_4_5 Html-Css
    linux服务器架设--学习笔记
    注解学习
    关于ruby gem源更新安装问题
    css3:2D与3D变形
    css3关键帧动画以及兼容性策略
    css3背景,蒙版,倒影以及过度
    阴影边框以及渐变
  • 原文地址:https://www.cnblogs.com/raphaelJava-4560/p/12976703.html
Copyright © 2011-2022 走看看