I am creating a shell program in java. For this purpose, I would like
to *immediately* read every key pressing. Eg. I would like to read
'\t', immediately, not after '\n' has been pressed. It seems that the
InputStream buffers all input until '\n' is pressed. Can I modify this
behaviour ?
Console buffering is done by the console, independent of Java. If you
can modify the console mode, then yes. On platforms where stty is
available, you can use something like this:
static String getInputMode() {
String mode = null;
try {
String[] cmd = {
"/bin/sh",
"-c",
"/bin/stty -g < /dev/tty"
};
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
mode = br.readLine();
p.waitFor();
br.close();
}
catch (IOException e) {} // should probably deal with this
catch (InterruptedException e) {}
return mode;
}
static void setInputMode(String mode) {
try {
String[] cmd = {
"/bin/sh",
"-c",
"/bin/stty " + mode + " < /dev/tty"
};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
catch (IOException e) {}
catch (InterruptedException e) {}
}
Then:
String savedMode = getInputMode();
try {
setInputMode("-icanon min 1");
doRestOfProgram();
}
finally {
setInputMode(savedMode);
}
Note that by doing this you lose the command line editing capabilities
normally provided by the console.
/gordon