Jdk9新特性增强try-with-resource
- 增强try-with-resource
在JDK9中,改进了try-with-resources语句,在try外进⾏初始化,在括号内引⽤,即可实现资源⾃动关闭,多个变量则⽤分号进⾏分割
不需要声明资源 out 就可以使⽤它,并得到相同的结果
- 代码案例
public class Main {
public static void main(String[] args)throws Exception {
String path = "/Users/xdclass/Desktop/t.txt";
test(path);
}
private static void test(String filepath) throws Exception {
OutputStream out = new FileOutputStream(filepath);
try(out) {
out.write((filepath+"可以学习java架构课程").getBytes());
}catch (Exception e){
e.printStackTrace();
}
}
}