标签: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掉
标签:nbsp 关闭 cep vat 文件 try print 需要 put
原文地址:https://www.cnblogs.com/zexin/p/12275948.html