如何在 while 循环中关闭 BufferedReader

How can I close BufferedReader in the while loop

当我试图在 while 循环中关闭 BufferedReader 时,它会在第二次执行循环时抛出 IOException: Stream closed

我的代码是这样的:

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

我应该怎么做才能关闭 BufferedReader?提前致谢。

你可以做几件事

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

如果您使用的是足够新的版本

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

如果发生异常,代码将立即进行到 catch 语句,然后是 finally 语句(如果存在)。

此外,异常处理的重点是处理可能发生的异常。您通常不希望在出现异常时退出系统——因为如果您无论如何都不处理异常,代码就会终止。

How can I close BufferedReader in the while loop

while 循环中关闭它,这就是 问题。

循环之前打开它,根本不要关闭它,因为它环绕在System.in周围,无法重新打开。