try-with-resources是一种简化资源管理的语法结构,用于自动关闭实现了 AutoCloseable或 Closeable接口的资源(如文件流、数据库连接等)- 在 try块执行完毕后(无论是否发生异常),系统会自动调用资源的 close()方法
- 关闭顺序与声明顺序相反(后声明的先关闭)
- 常见的如:InputStream, OutputStream, Connection, Statement等都已实现
vs传统写法
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try (FileInputStream fis = new FileInputStream("file.txt")) {
} catch (IOException e) {
e.printStackTrace();
}