• 《程序员修炼之道》-读书笔记二-资源管理语法 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();
    }
    }
    }
  • 相关阅读:
    7、Nginx基础Http原理
    8、nginx基础
    9、nginx常用基础模块
    第一章·MySQL介绍及安装
    第二章· MySQL体系结构管理
    第三章·MySQL版本区别及管理
    第四章· MySQL客户端工具及SQL讲解
    第五章· MySQL数据类型
    第六章· MySQL索引管理及执行计划
    第七章· MySQL的存储引擎
  • 原文地址:https://www.cnblogs.com/Deters/p/11143842.html
Copyright © 2020-2023  润新知