Java关闭流方法总结

 

Java 所有流都得在用完后关闭,避免造成资源浪费及攻击。

最老的try - catch - finally 很不优雅

private void trt_catch_finally(){
        String filepath = "a.xml";
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new FileReader(filepath);
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null)
                System.out.println(str);
        } catch (Exception e) {
        }
        finally {
            if(null != bf){
                try {
                    bf.close();
                } catch (IOException e) {
                }
            }
        }
    }

 

后来有段时间接触了org.apache.commons.io.IOUtils,会简洁一点点。点进源码看是他帮我们封装好了

private void IOUtils(){
        String filepath = "a.xml";
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new FileReader(filepath);
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null)
                System.out.println(str);
        } catch (Exception e) {
        }
        finally {
            IOUtils.closeQuietly(bf);
        }
    }
 

现在JDK7后,有了最新的try-with-resource,可以直接省略了关流,由JVM去处理

private void try_with_resource(){
        String filepath = "a.xml";
        try (BufferedReader bf = new BufferedReader(new FileReader(filepath))) {
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null)
                System.out.println(str);
        } catch (Exception e) {
        }
    }

 

你可能感兴趣的:(jdk,IOUtils)