How to use multiple Scanner objects on System.in?

2020-01-24 03:06发布

问题:

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 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. ?

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

回答1:

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.

Edit: "Details" on why multiple scanners are bad: Do not create multiple buffered wrappers on an 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.