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源码的学习也很重要!

  • 相关阅读:
    Regular进阶: 几点性能优化的建议
    总结常见的违背Rest原则的接口设计做法
    如何进行用户访谈更容易获得全面而有效的信息
    关于以太坊智能合约在项目实战过程中的设计及经验总结(2)
    关于以太坊智能合约在项目实战过程中的设计及经验总结(1)
    字节码执行方式--解释执行和JIT
    Redis数据库结构与读写原理
    移动端工程架构与后端工程架构的思想摩擦之旅(2)
    类文件结构与javap的使用
    JVM垃圾收集器(1)
  • 原文地址:https://www.cnblogs.com/zqsky/p/6898264.html
Copyright © 2011-2022 走看看