Java流关闭总结

ava中流中引用close方法总结

1.由Java.io包中的对象生成实例的close方法使用情况

BufferedInputStream bis = new BufferedInputStream(new InputStreamReader(new FileInputStream()))

BufferedInputStream类

public void close()
    throws IOException
  {
    byte[] arrayOfByte;
    while ((arrayOfByte = this.buf) != null)
    {
      if (!bufUpdater.compareAndSet(this, arrayOfByte, null))
        continue;
      InputStream localInputStream = this.in;
      this.in = null;
      if (localInputStream != null)
        localInputStream.close();
      return;
    }

BufferedInputStream中的close方法中的localInputStream参数的值就是在创建BufferedInputStream实例时传入的对象

InputStreamReader类

public void close()
    throws IOException
  {
    this.sd.close();
  }

InputStreamReader类中的close方法也是在创建InputStreamReader实例时传入的对象。


所以,在Java中使用流的组合时,只需要关闭最外层的流就会把所有在这个最外层中会引用到的流都关闭。

以上BufferedInputStream类和InputStreamReader类的源码皆取自在jdk中的rt.jar包中。

2.有Java.net.Socket 类获取到的流对象
  InputStream in = new Socket("ip",port).getInputStream();
  此类流的关闭情况如下:
  1.直接关闭socket:socket.close();在关闭socket的同时也会关闭由socket创建的流
  2.in.close() 在关闭流的同时也会关闭socket通讯,

原文地址:https://www.cnblogs.com/qinshou/p/7575589.html