传统 try-catch-finally
在java7以前,类似 IO 流操作时,要在 finally 代码块中关闭流,如下:
private static void readProperties() throws IOException {
try {
InputStream input = new FileInputStream("file.txt");
properties.load(input);
} finally {
if(input != null){
input.close();
}
}
}
Java7新特性
当类实现 java.lang.AutoCloseable 接口后,可以使用 try-with-resources 写法
在 try() 中写 创建流,并且不需要写 finally 代码块,IO 流会 自动关闭
private static void readProperties() throws IOException {
Properties properties = new Properties();
try(FileInputStream input = new FileInputStream("file.txt")) {
properties.load(input);
}
}
有catch写法
private static void readProperties() {
Properties properties = new Properties();
try(FileInputStream input = new FileInputStream("file.txt")) {
properties.load(input);
}catch (IOException e) {
throw e;
}
}