IOException:stream closed error while reading from console in java

3.5k Views Asked by At

I am calling the name_setter() method from the 'main' by creating an object of customer class to get the input from console and store the name entered in the 'name' variable of the object of the customer class.

import java.io.*;

public class Rental {

    public static void main(String[] args) {
        customer c = new customer();
        c.name_setter(); // calls the method from customer class
    }
}

class customer {
    String name;

    String name_setter() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter the name:"); // executes till here
            name = br.readLine(); // stream close error
            System.out.println(name);
            if (name.length() == 0) {
                name = br.readLine();
            }
        } catch (IOException e) {
            System.out.println("" + e);
        }

        return name;
    }
}

the error i am getting is:

java.io.IOException: Stream closed
1

There are 1 best solutions below

1
On

As Hovercraft Full Of Eels said, this code doesn't cause problem at runtime.
It is probably different from which one rises the exception : java.io.IOException: Stream closed.

Beware : you chain your BufferedReader with the System.in InputStream.
When you close the BufferedReader, it closes the System.in.

For example at the end of this code System.in is closed:

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

You should not close the BufferedReader if you want to read again in the System.in.
By deduction, I assume the problem comes from that.

You have the same problem with Scanner instances.