码迷,mamicode.com
首页 > 编程语言 > 详细

java输入,输出流如何无需finally关闭资源

时间:2020-02-08 13:54:48      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:nbsp   关闭   cep   vat   文件   try   print   需要   put   

例子:往一个文件内写东西

以前的写法,总是在流处理的最后都需要finally关闭资源,这样多了就会觉得很麻烦

    private static void oldtest(String filePath) throws FileNotFoundException {
        OutputStream out = new FileOutputStream(filePath);
        try {
            out.write((filePath+"我就是测试下用Java写点东西进来").getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                out.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

  Java7 里的try...catch...resource 写法可以流会自动回收,只需在try()括号里写流对象,这样就不用老是finally了

   //自动关闭资源写法
    private static void newtest(String filePath) throws FileNotFoundException {

        try(OutputStream out = new FileOutputStream(filePath);){
            out.write("用try...catch..resource写法试试会不会自动关闭资源".getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

  我们可以看下源代码:

技术图片

 

 

这个outputStream实现了Closeable这个类,看下Closeable源代码

技术图片

 

 

 看下AutoCloseable源代码:

技术图片

 

 

 注意:

   1、使用该写法,需要该类有有实现AutoCloseable类

   2、实现了AutoCloseable接?的类,在try()?声明该类实例的时候,try结束后?动调?的 close?法,这个动作会早于finally?调?的?法

   3、不管是否出现异常,try()?的实例都会被调?close?法

   4、try??可以声明多个?动关闭的对象,越早声明的对象,会越晚被close掉

 

java输入,输出流如何无需finally关闭资源

标签:nbsp   关闭   cep   vat   文件   try   print   需要   put   

原文地址:https://www.cnblogs.com/zexin/p/12275948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!