try}-with-resources

今天看前人代码的时候,发现了一个以前一直没用过的东西,

公司目前使用的是jdk1.8(vertx3需要),

在某处代码里有这样一行代码:

            try(
                FileOutputStream fos=new FileOutputStream(fileDir+File.separator+fileName,false);
                ) {
                ...
            } catch (IOException e) {
                e.printStackTrace();
                
            }

以前一直都是使用的try{}catch(){};但这里确是try(){}catch(){};

所以特地查了一下,发现:

总从jdk1.7后,java有一个这样的类:

java.lang.AutoCloseable.
源码中是这样描述该类的:
/**
 * An object that may hold resources (such as file or socket handles)
 * until it is closed. The {@link #close()} method of an {@code AutoCloseable}
 * object is called automatically when exiting a {@code
 * try}-with-resources block for which the object has been declared in
 * the resource specification header. This construction ensures prompt
 * release, avoiding resource exhaustion exceptions and errors that
 * may otherwise occur.
 *
 * @apiNote
 * <p>It is possible, and in fact common, for a base class to
 * implement AutoCloseable even though not all of its subclasses or
 * instances will hold releasable resources.  For code that must operate
 * in complete generality, or when it is known that the {@code AutoCloseable}
 * instance requires resource release, it is recommended to use {@code
 * try}-with-resources constructions. However, when using facilities such as
 * {@link java.util.stream.Stream} that support both I/O-based and
 * non-I/O-based forms, {@code try}-with-resources blocks are in
 * general unnecessary when using non-I/O-based forms.
 *
 * @author Josh Bloch
 * @since 1.7
 */

简单翻译就是:

在try() 中新建的文件流(或socket连接)对象,若该对象实现了接口java.lang.AutoCloseable,当try代码块结束的时候,该资源(文件流或socket连接)会被自动关闭.以达到自动释放资源,避免资源耗尽或报错的发生.

同时,注释中也表示,对于一些同时支持io和nio的类,比如java.util.stream.Stream,就无所谓使用哪种方式.

java源码的学习也很重要!

原文地址:https://www.cnblogs.com/zqsky/p/6898264.html