Because when you close the BufferedReader
all the underlying streams are closed. THis is the case with all the classes that wrap and read/write from/to streams.
This is a convenience so that you don't need to go through the entire set of objects you've instantiated (the InputStream
, the InputStreamReader
and finally the BufferedReader
) and close all of them.
A simple test will demonstrate this:
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.close();
// Will throw IOException
int i = System.in.read();
}
System.in
isn't special; it's an InputStream
. The same thing would happen if the underlying stream was say, a FileInputStream
rather than stdin
:
public static void main(String[] args) throws IOException
{
File f = new File("SomeFileName");
FileInputStream fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
br.close();
// throw IOException
int i = fis.read();
}
Given that usually these constructors are chained (as they are in your example), it would be annoyingly cumbersome to have to retain and close each one.
Imagine having to do the following every time you wanted to use streams:
public static void main(String[] args) throws IOException
{
File f = new File("SomeFileName");
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(irs);
// Use the BufferedReader
br.close();
isr.close();
fis.close();
}