Skip to content

Instantly share code, notes, and snippets.

@rhaseven7h
Created June 10, 2016 20:59
Show Gist options
  • Save rhaseven7h/3cd6f5baee4f141d19d389d1c321390e to your computer and use it in GitHub Desktop.
Save rhaseven7h/3cd6f5baee4f141d19d389d1c321390e to your computer and use it in GitHub Desktop.
Get single character in java console (terminal, blocking call)
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();
}
}
@PicassoCT
Copy link

Doesent work - throws Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.Console.reader()" because "console" is null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment