Java catch Ctrl+D EOF
REPL
and other command line programs can catch Ctrl+D EOF in Java in a platform-independent way.
Assuming
java.util.Scanner
is used to read input from the command line, the code for Ctrl+D EOF detection works by catching EOF by scanner.hasNextLine()
method, and also catches
Ctrl+D EOF
by checking for Unicode character \u0004
in stdin pipe.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String argument = "";
final String prompt = "MyREPL> ";
System.out.print(prompt);
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
String[] inputArray = input.split(" ");
String command = inputArray[0];
if (inputArray.length > 1) {
argument = inputArray[1];
} else {
argument = "";
}
if (command.equals("exit") || command.equals("\u0004")) {
break;
}
// main program logic here
}
}
}