try(){}catch(){} 自动资源释放
从jdk7 build 105 后, 编译器和运行环境就开始支持新的"try catch" 语句, 简单来讲就是个语法糖
tip: 写在try()里面的流对象对应的类都实现了自动关闭接口AutoCloseable;
举个栗子
public class TestTryCatch {
public static void main(String[] args) {
// 以channel为例 这个channel会在try执行完毕后自动关闭
try (FileChannel channel = new RandomAccessFile("xxx.txt", "r").getChannel()) {
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个语法糖全称叫 try-with-resources语句 缩写twr
idea快捷键: .twr
idea快捷键: .twr
idea快捷键: .twr
重要的事说三遍