Search code examples
javainputstreambufferedreader

Exception in thread "main" java.io.IOException: Stream closed : BufferedReader class


void order_particular() throws IOException{
        int order_choice, x;
        //Scanner sc = new Scanner(System.in);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Do you want to order something ? ");
        System.out.println("Press 1 to order or 0 to go back to main menu");
        //order_choice = sc.next().charAt(0);
        order_choice = Integer.parseInt(reader.readLine());  // Got Error here
        System.out.println("order choice : " + order_choice);
        if(order_choice == 1){
            this.order();
            System.out.println("Do you want to order more ? ");
            System.out.println("Press 1 to order or 0 to get bill");
            x = Integer.parseInt(reader.readLine());
            System.out.println("x value : " + x);
            if(x == 1){
                this.order_more();
                this.bill_more();
            }
            else
                this.bill();
        }
    }

For the above code, I got the below error

Exception in thread "main" java.io.IOException: Stream closed
        at java.base/java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:168)
        at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:334)
        at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:270)
        at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:313)
        at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188)
        at java.base/java.io.InputStreamReader.read(InputStreamReader.java:177)
        at java.base/java.io.BufferedReader.fill(BufferedReader.java:162)
        at java.base/java.io.BufferedReader.readLine(BufferedReader.java:329)
        at java.base/java.io.BufferedReader.readLine(BufferedReader.java:396)
        at Waiter.order_particular(Waiter.java:404)
        at Waiter.main(Waiter.java:439)

I don't know what is going on here. I never closed bufferedReader object, But it shows an error. How to solve this error?


Solution

  • The exception indicates that it is System.in that has been closed already by this point.

    You'll need to look at what's happening before calling order_particular(), as the problem lies there. Maybe an earlier method is inadvertently closing it; perhaps you created a BufferedReader around it in a try-with-resource block.