Java高级特性: try-with-resource

try-with-resource

    • 语法介绍

语法介绍

我们在使用一些资源的时候,比如文件句柄,输入输出流,需要在使用结束时释放相关资源,调用close接口。
通常我们的写法是用try-catch将功能代码包起来,然后在finally里面,释放资源。
try-with-resoure

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using “try-with-resources” pattern and will be closed automatically.

Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box it’s on to their knees.

你可能感兴趣的:(Java)