包裝流的close方法是否會自動關閉被包裝的流?
平時我們使用輸入流和輸出流一般都會使用buffer包裝一下,
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOTest {
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("c:\\a.txt");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write("test write something".getBytes());
bufferedOutputStream.flush();
//從包裝流中關閉流
bufferedOutputStream.close();
}
}
通過觀察各種流的源代碼,可得結論:包裝的流都會自動調用被包裝的流的關閉方法,無需自己調用。
可以看到BufferedOutputStream調用super(out);,也就是說,out.close();調用的是通過BufferedOutputStream傳入的被包裝的流,這裏就是FileOutputStream。
我們在看看其他類似的,比如BufferedWriter的源代碼
public void close() throws IOException {
synchronized (lock) {
if (out == null) {
return;
}
try {
flushBuffer();
} finally {
out.close();
out = null;
cb = null;
}
}
}
————————————————
一個流上的close方法可以多次調用,理論上關閉流不需要考慮順序,但有時候關閉方法中調用了write等方法時會拋異常;