8

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.

ghostdog74
  • 307,646
  • 55
  • 250
  • 337

1 Answers1

13

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.

  • broken link looks like it should be --> https://www.securecoding.cert.org/confluence/display/java/FIO06-J.+Do+not+create+multiple+buffered+wrappers+on+a+single+byte+or+character+stream – jacobq Sep 20 '15 at 03:42