JDK8新特性之 try-with-resources
(供笔者学习记录)
什么是try-with-resources
- 资源的关闭很多⼈停留在旧的流程上,jdk7新特性就有,但是很多⼈以为是jdk8的 在try( …)⾥声
明的资源,会在try-catch代码块结束后⾃动关闭掉 - 旧的方式:
public static void main(String[] args) throws IOException {
String path = "/Users/a.txt";
test(path);
}
private static void test(String filepath) throws FileNotFoundException {
OutputStream out = new FileOutputStream(filepath);
try {
out.write((filepath+"abc程").getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 新的方式
private static void test(String filepath){
try(OutputStream out = new FileOutputStream(filepath);) {
out.write((filepath+"abc程").getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
- 注意点 :实现了AutoCloseable接⼝的类,在try()⾥声明该类实例的时候,try结束后⾃动调⽤的
close⽅法,这个动作会早于finally⾥调⽤的⽅法 - 不管是否出现异常,try()⾥的实例都会被调⽤close⽅法
- try⾥⾯可以声明多个⾃动关闭的对象,越早声明的对象,会越晚被close掉
JDK9新特性之增强try-with-resource
- 在JDK9中,改进了try-with-resources语句,在try外进⾏初始化,在括号内引⽤,即可实现
资源⾃动关闭,多个变量则⽤分号进⾏分割 - 不需要声明资源 out 就可以使⽤它,并得到相同的结果
public static void main(String[] args) throws Exception {
String path = "/Users/a.txt";
test(path);
}
private static void test(String filepath) throws FileNotFoundException {
OutputStream out = new FileOutputStream(filepath);
try (out) {
out.write((filepath + "abc程").getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}