문제

I was wondering why I get a java.io.IOException: Stream closederror when using

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

In 2 different classes.

The setup is as follows.

public class SomeClass{

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //br.readSomeStuff
    br.close();

    new SomeOtherClass(); //defo not passing the br along to the new class!

}
public class SomeOtherClass{

    public SomeOtherClass(){
        method():
    }

    private void method(){
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
        br.readLine();
        // results into an IOEXCEPTION Stream close
    }

}

The issue is gone when I close the BufferedReader in the first class AFTER the creation of the other class. I dont understand why this would give issues though. I am creating a new BufferedReader on System.in, why could this possibly result into a stream closed error?

Similar question here. Does not explain WHY System.in is closed for some reason though.

Thanks in advance!

도움이 되었습니까?

해결책

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();

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top