[英]How to use multiple Scanner objects on System.in?
what's the correct way to use multiple Scanner objects in my program. 在我的程序中使用多个Scanner对象的正确方法是什么。 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 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()
? 我需要使用
userInput.close()
吗? What am i doing wrong. 我究竟做错了什么。 ?
?
What I don't understand is, the first System.in
is just getting the file name. 我不明白的是,第一个
System.in
只是获取文件名。 After that, why does it interfere with the second System.in
. 之后,为什么它会干扰第二个
System.in
。 As for the input
object, its reading from a File and not from System.in
. 至于
input
对象,它从File而不是System.in
读取。
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 close
method) 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? 另请参阅Java代码问题...扫描程序相关? which also talks about some approaches.
这也谈到了一些方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.