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

原文地址:https://www.cnblogs.com/raphaelJava-4560/p/12976703.html