zoukankan      html  css  js  c++  java
  • 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源码的学习也很重要!

  • 相关阅读:
    CodeForces 55D Beautiful numbers(数位dp+数学)
    hdu 2089 不要62(数位dp入门)
    Git版本控制
    Git初始化-添加提交以及查看状态
    linux-高并发与负载均衡-lvs-3种模型推导
    Scrapy中选择器的用法
    Scrapy命令行详解
    Scrapy框架基本用法讲解
    MaxCompute教程
    Scrapy安装报错
  • 原文地址:https://www.cnblogs.com/zqsky/p/6898264.html
Copyright © 2011-2022 走看看