Home > Software engineering >  EoF System.in processing
EoF System.in processing

Time:03-26

Scanner scanner=new Scanner(System.in);        

String s1=scanner.nextLine();         
String s2= scanner.nextLine();

I need to write EoF(ctrl D) at the first input. How can I process it so that stdin doesn't close and I can continue to receive input

CodePudding user response:

You can't. Once EOF is reached, the input stream is in an invalid state for further reading.

If you need to signal something similar to EOF but allow reading subsequently, you must use some special input data that is recognized by the program.

There are ugly hacks to prevent Ctrl D from being recognized as EOF: How do I reopen System.in after EOF or prevent EOF entirely?. Also see https://stackoverflow.com/a/1066647/18157.

CodePudding user response:

You can simply reopen the Scanner the same way you did originally:

import java.util.*;

class Foo {
  public static void main(String[] args) {
    Scanner scanner=new Scanner(System.in);
    System.err.println("Enter some text and hit some Ctr D");
    while (true) {
      try {
        String s = scanner.nextLine();
        System.out.println("You wrote: "   s);
      } catch(NoSuchElementException e) {
        System.err.println("EOF. Retrying.");
        scanner = new Scanner(System.in);        // HERE
      }
    }
  }
}

Note that this is an infinite loop if the stream flags EOF forever, such as when piping or redirecting a file, so it's your responsibility to verify that stdin is a tty and/or add a retry limit.

  • Related