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通訊,