使用try获取标准输入流报错StreamClosed坑

2022-06-25 13:48:13
void standardInputStream(){
    int by;
    while(true){
        try (
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        ) {
            String tmp;
            while ((tmp = in.readLine()) != null) break;
            System.out.println("your input is:" + tmp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这么写会导致System.in这个标准输入流被关闭,从而导致后面报错,正确的写法是不应该将BufferReader写进小括号内。

  • 作者:qq_30499345
  • 原文链接:https://blog.csdn.net/qq_30499345/article/details/122547283
    更新时间:2022-06-25 13:48:13