代码之家  ›  专栏  ›  技术社区  ›  ghostdog74

如何在System.In上使用多个扫描仪对象?

  •  7
  • ghostdog74  · 技术社区  · 14 年前

    在我的程序中使用多个扫描仪对象的正确方法是什么?例如,我使用scanner读取文件,然后根据在文件中找到的内容,再次使用scanner提示用户输入。显示了我的代码摘录

    ....
    Scanner f = new Scanner (System.in); //get the file name
    String fileName = f.next();
    Scanner input = new Scanner( new File( fileName ) );
    while ( input.hasNext() )
    {
       String currentLine = input.nextLine();
       if ( some pattern found) {
           Scanner getUserInput = new Scanner (System.in);
           String userInput = getUserInput.next();
           .....
       }
    }
    ....
    

    它似乎不起作用。我需要用吗 userInput.close() ?我做错什么了。?

    我不明白的是,第一个 System.in 正在获取文件名。在那之后,为什么它会干扰第二个 程序输入 . 至于 input 对象,从文件读取而不是从 程序输入 .

    1 回复  |  直到 14 年前
        1
  •  11
  •   user166390    7 年前

    我做错什么了?

    在同一个流上使用多个扫描仪是根本问题。扫描仪可以(并且将)消耗流-这可能(将)导致意外的副作用。最好不要这样做。

    如果输入关闭,则输入(但字符串没有 close 方法)对每个人都是封闭的-这对任何人都不是什么乐趣。

    编辑: 有关多台扫描仪损坏原因的“详细信息”: Do not create multiple buffered wrappers on an InputStream

    …任何缓冲包装都是不安全的;如果使用扫描仪,这种情况也是可利用的…

    另请参见 Java code question ... scanner related? 同时也谈到了一些方法。