zoukankan      html  css  js  c++  java
  • 《程序员修炼之道》-读书笔记二-资源管理语法 try-with-resources(TWR)

    Coin项目:资源管理语法 try-with-resources(TWR)

    今天刚学的新的资源管理语法 try-with-resources,它是在Java 7的新特性,借助编译器来实现的这项改进。

    下面来看,之前我们要关闭资源时,通常都是在finally语句块中进行资源的关闭,需要写大量代码,虽然写起来很简单,但是却很多,浪费时间。

    而且还有可能忘记关闭某个流,造成内存泄漏,这是有可能发生的。

    但是当我们使用 try-with-resources时,就可不必在担心这个了,将资源统一放入try的圆括号内,由编译器在资源处理完成后自动关闭,大大提高了我们的编程效率

    public class Test {
    public static void main(String[] args) {

    try (FileInputStream fileInputStream = new FileInputStream(new File("test.txt"));
    FileOutputStream fileOutputStream = new FileOutputStream(new File("out.txt"));
    BufferedInputStream bin = new BufferedInputStream(fileInputStream);
    BufferedOutputStream bout = new BufferedOutputStream(fileOutputStream)
    ) {
    int b;
    while ((b = bin.read()) != -1) {
    bout.write(b);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
  • 相关阅读:
    拥抱函数式编程 I
    关于CMS的那点事 I
    常用正规表达式
    javascript source map 的使用
    架构师修炼 后记
    CSS 天坑 I
    架构师修炼 III
    架构师修炼 II
    win10,VM14 安装cnetos6.9 虚拟机黑屏和只有光标闪烁解决办法
    C/C++数组初始化
  • 原文地址:https://www.cnblogs.com/Deters/p/11143842.html
Copyright © 2011-2022 走看看