Fingalzzz
Fingalzzz

Reputation: 109

How can I close BufferedReader in the while loop

When I was trying to close the BufferedReader in the while loop, it will throws an IOException: Stream closed when the loop execute the second time.

My code is like:

import java.io.*;

class Test {
    public static void main(String[] args) {
        int option = 0;
        BufferedReader br = null;
        while (option != -1) {
            try {
                br = new BufferedReader(new InputStreamReader(System.in));
                try {
                    option = Integer.parseInt(br.readLine());
                } catch (NumberFormatException e) {
                    option = -1;    
                }

                br.close();
            } catch (IOException e) {
                System.err.println(e);
                System.exit(-4);
            }

            System.out.println(option);
        }
    }
}

What should I do to close BufferedReader? Thanks in advance.

Upvotes: 0

Views: 727

Answers (2)

user207421
user207421

Reputation: 310868

How can I close BufferedReader in the while loop

You are closing it in the while loop, and that's the problem.

Open it before the loop, and don't close it at all, as it's wrapped around System.in, which can't be reopened.

Upvotes: 3

jrhee17
jrhee17

Reputation: 1152

You can do a couple of things

    try {
           br = new BufferedReader(new InputStreamReader(System.in));
           try {
                option = Integer.parseInt(br.readLine());
            } catch (NumberFormatException e) {
                option = -1;    
            }

            br.close();
        } catch (IOException e) {
            System.err.println(e);
            br.close();
            System.exit(-4);
        }
 }

If you're using a recent enough version

    try {
           br = new BufferedReader(new InputStreamReader(System.in));
           try {
                option = Integer.parseInt(br.readLine());
            } catch (NumberFormatException e) {
                option = -1;    
            }
        } catch (IOException e) {
            System.err.println(e);
            System.exit(-4);
        } finally {
            br.close();
        }

If an exception is incurred, the code will progress immediately to the catch statement, and then the finally statement if it exists.

Also, the whole point of exception handling is to take care of a exception that might happen. You normally wouldn't want to exit a system in an exception--since the code will terminate if you didn't handle the exception anyways.

Upvotes: -1

Related Questions