《程序员修炼之道》-读书笔记二-资源管理语法 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();
}
}
}
原文地址:https://www.cnblogs.com/Deters/p/11143842.html