9

What's the correct way to use multiple Scanner objects in my program?

For example, I use the scanner to read a file, then depending on what is found in the file, I prompt for user input and use the scanner again.

Here is an extraction of my code:

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. What am I doing wrong?

Do I need to use userInput.close()?

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, it's reading from a file and not from System.in.

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
ghostdog74
  • 327,991
  • 56
  • 259
  • 343

1 Answers1

14

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 a single byte or character stream

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

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
  • 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