AutoCloseable
该接口用于try-with-resources语法糖提供支持,用于自动关闭资源作用
- 类型:接口
- 方法:close();
- 详解:
- close():用于自动关闭资源的时候需要进行调用该方法,该方法声明中设置了抛出Exception异常
-
- 注意事项:
- 虽然其抛出的Exception异常,但是在注释上说明了最好不要在代码中抛出中断异常(InterruptedException),也就是说需要对中断类型的异常进行捕获
- 由于基本上子类实现的
close
方法最后调用的基本上都是本地方法。
- 注意事项:
例子:
public class AutoCloseableTest {
@Test
public void test(){
try(FileInputStream inputStream=new FileInputStream(new File("test.txt"))){
//do somethings
} catch (IOException e) {
e.printStackTrace();
}
//不需要在使用finally去关闭资源了,方便快捷
}
}