如何在System.in上使用多个Scanner对象?

gho*_*g74 7 java inputstream java.util.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();
       .....
   }
}
....
Run Code Online (Sandbox Code Playgroud)

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

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

小智 11

我究竟做错了什么?

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

如果输入已关闭,那么close每个人都会关闭输入(但字符串没有方法) - 这对任何人来说都不是很有趣.

编辑:关于多个扫描程序错误原因的"详细信息":不要在InputStream上创建多个缓冲包装器

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

另请参阅Java代码问题...扫描程序相关?这也谈到了一些方法.