Created
June 10, 2016 20:59
-
-
Save rhaseven7h/3cd6f5baee4f141d19d389d1c321390e to your computer and use it in GitHub Desktop.
Get single character in java console (terminal, blocking call)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Console; | |
import java.io.IOException; | |
import java.io.Reader; | |
import java.lang.Runtime; | |
public class Main { | |
public static void main(String[] args) throws IOException, InterruptedException { | |
System.out.println("Press the \"z\" key to exit!"); | |
String[] cmd = {"/bin/sh", "-c", "stty raw </dev/tty"}; | |
Runtime.getRuntime().exec(cmd).waitFor(); | |
Console console = System.console(); | |
Reader reader = console.reader(); | |
while (true) { | |
int r = reader.read(); | |
System.out.printf("%s\r\n", r); | |
if (r == 122) { // "z" character | |
break; | |
} | |
} | |
cmd = new String[] {"/bin/sh", "-c", "stty sane </dev/tty"}; | |
Runtime.getRuntime().exec(cmd).waitFor(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesent work - throws Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.Console.reader()" because "console" is null