Search code examples
javainputstreamjava.util.scanner

How to use multiple Scanner objects on System.in in Java?


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.


Solution

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