【问题标题】:Odd error related to Stream being closed与 Stream 关​​闭相关的奇怪错误
【发布时间】:2015-01-11 07:42:30
【问题描述】:

我正在学习 Java,我编写了一个方法来更新文件中的记录。我遇到的问题是,当我询问用户是否要查找另一个文件时,我的阅读器已关闭或无法为其分配任何输入。

protected boolean Update() throws InputMismatchException
{
    RoomService Init =new RoomService();
    Scanner input = new Scanner(System.in);

        try {
            boolean ans= true;

         while(ans)
         {
            System.out.println("Please enter room number.");
            String id = input.next();
            Init.Update(id);
            System.out.println("Press Enter to Add more or no to exit");
            String choice = input.nextLine();// Skips this line 
                if (choice.equalsIgnoreCase(""))
                {
                    continue;
                }
                else if(choice.equalsIgnoreCase("no"))
                {
                    ans= false;
                }
                  else 
                  {
                      System.err.println("Wrong input");
                        throw new IOException();
                  }
         }

        } catch (IOException e) {
            e.printStackTrace();
            fail=true;
        }
    return fail;
}

想知道究竟是什么阻止我输入我也使用过的任何东西BufferedReader input = new BufferedReader(new InputStreamReader (System.in))

谢谢。

编辑:

使用扫描仪错误是:java.util.NoSuchElementException

使用 BufferedReader 错误是:java.io.IOException: Stream closed

【问题讨论】:

  • 您得到的确切错误信息是什么?

标签: java input stream java.util.scanner bufferedreader


【解决方案1】:

如果您的代码中的其他任何地方都在使用 Scanner 包裹在 System.in 周围,请确保不要在其上调用 close()Scanner 本身没有需要关闭的资源,除非您想要关闭底层输入源,而对于包裹在 System.in 周围的 Scanner,您不需要关闭,因为这会阻止所有未来的输入。

【讨论】:

  • 我没有,因为我使用我的 View 和 Add 函数,当循环它只是这个更新方法时,它们都接受输入。如果我对 Streams 有更多的了解,不确定是否有其他东西正在关闭它。
  • 尝试单独运行Update 方法。如果它不再抛出异常,您就知道问题在于您的代码的某些部分正在关闭System.in。然后将部分代码一次又一次地放回原处,以确定是哪一部分在执行此操作。
  • 认为是这种情况,但我不确定,当您从 try-catch 资源中的函数返回时,它是否仍会关闭资源?
  • try-with-resources statement(例如,try (Scanner input = new Scanner(System.in)) { ... })在您退出 try 块时会关闭资源。这就是重点。 regular try statement 不会自行关闭任何内容。
  • 发现它显然是什么我有一个抑制警告因此我没有看到资源泄漏。
猜你喜欢
  • 2016-05-10
  • 2023-04-08
  • 1970-01-01
  • 2011-05-29
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2012-04-08
  • 2016-07-07
相关资源
最近更新 更多