try-with-resource 自动关闭Closeable接口的资源
Java中,JVM的垃圾回收机制可以对内部资源实现自动回收,给开发者带来极大的遍历,但是JVM对外部资源(调用了底层操作系统的资源)的引用却无法自动回收,例如数据库连接,网络连接以及输入输出IO流等。这些连接就需要我们手动去关闭,不然会导致外部资源泄露,连接池溢出以及文件被异常占用等。
JDK7之后,新增了“try-with--resource”。它可以自动关闭实现了AutoCloseable接口的类,实现类需要实现close()方法。“try-with-resources”声明,将try-catch-finally简化为try-catch,这其实是一种语法糖,字编译时仍然会转化为try-catch-finally语句;
如下FileReader:
以下两种都是关闭了流资源reader:
public class CloseTest {
public static void main(String[] args) {
FileReader reader =null;
try {
reader = new FileReader("D:\\huangzheng\\a.txt");
}catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
package com.to.filter;
import java.io.FileReader;
import java.io.IOException;
public class CloseTest {
public static void main(String[] args) {
try (FileReader reader = new FileReader("D:\\huangzheng\\1.txt");)
{
char[] a = new char[1024];
int read = reader.read(a);
String s = new String(a, 0, read);
System.out.println(s);
}catch (IOException e) {
e.printStackTrace();
}
}
}
try{}中写流关闭,如果发生异常不会关闭流,所以要么使用finally或者try()中实现流的关闭
对比:try-with-finally:是手动关流
try-with-resource:自动关流,就是写在try()中,语法糖看起来很别扭