try-with-resource 自动关闭 AutoClosable 接口的资源
JAVA 中,JVM 的垃圾回收机制可以对内部资源实现自动回收,给开发者带来了极大的便利。但是 JVM 对外部资源(调用了底层操作系统的资源)的引用却无法自动回收,例如数据库连接,网络连接以及输入输出 IO 流等。这些连接就需要我们手动去关闭,不然会导致外部资源泄露,连接池溢出以及文件被异常占用等。JDK7 之后,新增了“ try-with-resource”。它可以自动关闭实现了AutoClosable 接口的类,实现类需要实现 close()方法。”try-with-resources 声明”,将 try-catch-finally 简化为 try-catch,这其实是一种语法糖,在编译时仍然会进行转化为 try-catch-finally 语句。
常见的实现了AutoCloseable接口的类有:
BufferedInputStream, BufferedOutputStream
BufferedReader, BufferedWriter
FileInputStream, FileOutputStream
FileReader, FileWriter
InputStream, OutputStream
PrintWriter, PrintStream
Reader, Writer
Scanner, SSLServerSocker, SSLSocket等等等等
举例说明
try–catch-finally 实现
Scanner scanner = null;
try {
scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
try-with-resources 实现
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}