zoukankan      html  css  js  c++  java
  • Apache common-io AutoCloseInputStream 分析

    Apache common-io 包是常用的工具包,他提供了对IO操作的一些封装。首先看一下input包下的 AutoCloseInputStream 类

       1:   * This class is typically used to release any resources related to an open
       2:   * stream as soon as possible even if the client application (by not explicitly
       3:   * closing the stream when no longer needed) or the underlying stream (by not
       4:   * releasing resources once the last byte has been read) do not do that.
       5:   *
       6:   * @version $Id: AutoCloseInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $
       7:   * @since 1.4
       8:   */
       9:  public class AutoCloseInputStream extends ProxyInputStream 

    这个类的作用是自动关闭使用的流,具体的实现是每次 read 的时候,都判断一下是否返回的是 -1,是就立马关闭。

        @Override
        protected void afterRead(int n) throws IOException {
            if (n == -1) {
                close();
            }
        }

    实现非常简单,但是这里提供了一个非常好的设计。首先,实现了一个抽象类ProxyInputStream,继承该类,通过集成该抽象类,只需要很简单重写 afterRead 类就可以达到每次read 都判断是否应该关闭。

    image

    在ProxyInputStream中的所有read方法中,在read之前之后分别调用  beforeRead  以及 afterRead方法,这样在之类中通过覆写 beforeRead 以及 afterRead方法,来做我们想做的事情。

        protected void beforeRead(int n) throws IOException {
        }
     
        protected void afterRead(int n) throws IOException {
        }
     
        @Override
        public int read() throws IOException {
            try {
                beforeRead(1);
                int b = in.read();
                afterRead(b != -1 ? 1 : -1);
                return b;
            } catch (IOException e) {
                handleIOException(e);
                return -1;
            }
        }
    
    
        @Override
        public int read(byte[] bts, int off, int len) throws IOException {
            try {
                beforeRead(len);
                int n = in.read(bts, off, len);
                afterRead(n);
                return n;
            } catch (IOException e) {
                handleIOException(e);
                return -1;
            }
        }

    所以在AutoCloseInputStream  中,只通过重写了 afterRead方法,每次read都判断是否为 –1 ,是则关闭流。

  • 相关阅读:
    git怎么创建本地版本仓库
    win7系统下,vs2010一调式,vs就关闭要重启
    ASP.NET常见面试题及答案(130题)
    easyui日期在未加载easyui-lang-zh_CN.js出现英文的情况下加载中文的方法
    LigerUi框架+jquery+ajax无刷新留言板系统的实现
    asp.net正则模板引擎代码
    SubSonic2.2框架的使用方法和配置说明
    LigerUI一个前台框架增、删、改asp.net代码的实现
    自定义easyui整数或者数字、字母或者下划线验证方法
    VS2010在64位系统中连接64位Oracle出现的问题和解决方法
  • 原文地址:https://www.cnblogs.com/atio/p/3517073.html
Copyright © 2011-2022 走看看