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 都判断是否应该关闭。

在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 ,是则关闭流。

最新文章

  1. 关于asp.net利用mono部署到Linux上的一些说明
  2. C#基础---C#如何对Json字符串处理
  3. [HOOLOO] zizaco/entrust 5.2.x-dev Class name must be a valid object or a string
  4. Python创建Cocos2d-x 2.2方法
  5. goldengate 12c 针对oracle 12c配置的主要变化
  6. linux下proc目录详解
  7. 用户向导页面实现左右滑动的ImageSwitcher
  8. Java 反射 调用私有域和方法(setAccessible)
  9. 使用JDB调试Java程序
  10. Spring加载XML机制
  11. RabbitMQ可靠性投递及高可用集群
  12. Mysql 导入CSV文件,中文内容乱码问题
  13. xcode工程编译错误之iOS解决CUICatalog: Invalid asset name supplied问题
  14. cmake编译obs
  15. Tomcat修改用户名密码教程
  16. JavaScript学习总结(三、函数声明和表达式、this、闭包和引用、arguments对象、函数间传递参数)
  17. mysql 多个字段 order by
  18. Python学习---Form拾遗180322
  19. 关于Unity中物理引擎的使用
  20. python基础(5)

热门文章

  1. Windows中报错:Fatal error in launcher: Unable to create process using '"' 的解决方案
  2. Bootstrap中的Glyphicon 字体图标
  3. LUNA16数据集(二)肺结节可视化
  4. java 获取 正在执行的方法名
  5. php中静态绑定
  6. shell编程上
  7. Android MVP模式实现组件和业务逻辑分离
  8. daterangepicker-双日历
  9. 1.3 IDAE安装GO插件
  10. java list分页