在Java中多次读取System.in会导致IOException?

在Java中多次读取System.in会导致IOException?,java,Java,我正在尝试创建一个小的命令行游戏,以加强我在过去几个月里在Java中学到的一些东西 我试图创建一个名为readInput()的方法,该方法返回一个字符串,我可以反复调用该字符串。第一次工作正常,第二次却导致IO.Exception。如果我删除语句bisr.close();它可以工作,但被教导关闭溪流,因为让溪流开着是不好的做法 有没有人能帮我指出正确的方向,因为我已经在谷歌上搜索过了,但是没有用 方法 private String readInput() { String input =

我正在尝试创建一个小的命令行游戏,以加强我在过去几个月里在Java中学到的一些东西

我试图创建一个名为readInput()的方法,该方法返回一个字符串,我可以反复调用该字符串。第一次工作正常,第二次却导致IO.Exception。如果我删除语句bisr.close();它可以工作,但被教导关闭溪流,因为让溪流开着是不好的做法

有没有人能帮我指出正确的方向,因为我已经在谷歌上搜索过了,但是没有用

方法

private String readInput()
{
    String input = null;
    BufferedReader bisr = null;
    try
    {
        bisr = new BufferedReader(new InputStreamReader(System.in));
        input = bisr.readLine();
    }
    catch (Exception e)
    {
        System.out.println("Error: " + e);
    }
    finally
    {
        try
        {
            bisr.close();
        }
        catch (Exception e)
        {
            System.out.println("Error:" + e);
        }
        return input;
    }
}
第一次工作正常,第二次出现IO异常

bisr.close()
还将关闭底层输入流(在本例中为
System.in
)。这就是为什么连续读取会导致IOException

如果我删除语句bisr.close();它可以工作,但被教导关闭溪流,因为让溪流打开是不好的做法

在执行期间保持
系统处于打开状态没有问题

如果不想创建不必要的多个对象,可以创建一次BufferedReader,并传递它

对于这种特殊情况,我可能会选择

private String readInput() {
    return new Scanner(System.in).nextLine();
}

问题在于,关闭
BufferedReader
也会自动关闭
InputStreamReader
,从而隐式关闭
系统

第二次调用该方法时,
System.in
已关闭,这意味着您将无法从中读取


“始终关闭它”只适用于您也打开的资源

对于System.in,最好有一个全局缓冲读取器或扫描程序,您只需创建一次。这是因为BufferedReader和Scanner可以读取多行数据,它会缓冲多行数据以提高性能,因此您可能会丢弃某些行或部分行

public static void main(String... args) throws  InterruptedException {
  for(int i=0;i<5;i++) {
    System.out.println("\nread "+readLine());
    // give me time to write more than one line, no problem from a file.
    Thread.sleep(1000);
  }
}

public static String readLine() {
  // can lose input.
  return new Scanner(System.in).nextLine();
}
如果我使用全局扫描对象并执行相同的操作

static final Scanner IN = new Scanner(System.in);

public static void main(String... args) throws InterruptedException {
  for (int i = 0; i < 10; i++) {
    System.out.println("\nread " + readLine());
    // give me time to write more than one line, no problem from a file.
    Thread.sleep(1000);
  }
}

public static String readLine() {
  return IN.nextLine();
}

是的,看起来好多了,很有道理。谢谢你
static final Scanner IN = new Scanner(System.in);

public static void main(String... args) throws InterruptedException {
  for (int i = 0; i < 10; i++) {
    System.out.println("\nread " + readLine());
    // give me time to write more than one line, no problem from a file.
    Thread.sleep(1000);
  }
}

public static String readLine() {
  return IN.nextLine();
}
1

read 1
2
3
4
read 2

5
6
read 3

7
8

read 4
9

read 5
0

read 6

read 7

read 8

read 9

read 0