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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4232588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:26:20  来源:igfitidea点击:

How to use multiple Scanner objects on System.in?

javainputstreamjava.util.scanner

提问by ghostdog74

what's the correct way to use multiple Scanner objects in my program. For example, I use scanner to read a file, then depending on what is found in the file, i use scanner again to prompt for user input. An extract of my code is shown

在我的程序中使用多个 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();
       .....
   }
}
....

It doesn't seem to work. Do I need to use userInput.close()? What am i doing wrong. ?

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

What I don't understand is, the first System.inis just getting the file name. After that, why does it interfere with the second System.in. As for the inputobject, its reading from a File and not from System.in.

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

回答by

What am I doing wrong?

我究竟做错了什么?

Using multiple scanners on the same stream is the underlying problem. Scanners can (and will) consume the stream - this may (will) lead to unexpected side-effects. Best not to do it.

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

If the input is closed, then the input (but Strings have no closemethod) is closed for everyone - and that's not much fun for anyone.

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

Edit:"Details" on why multiple scanners are bad: Do not create multiple buffered wrappers on an InputStream

编辑:关于为什么多个扫描器不好的“详细信息”:不要在 InputStream 上创建多个缓冲包装器

...any buffered wrapper is unsafe; this condition is also exploitable if a Scanner is used instead...

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

See also Java code question ... scanner related?which also talks about some approaches.

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