Immediately reading characters from System.in

F

frankgerlach22

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 ?
 
G

Gordon Beaton

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
 
R

Raymond DeCampo

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 ?

If you want to stay platform-independent, I recommend using Swing or AWT
to display a text area for input and output. Then you will have full
control.

HTH,
Ray
 
R

Roedy Green

So JNI is the answer.

that's one way if your platform has a getc.

The other is to fake something with AWT keystroke events.

These you do get as they happen.

The other half of the problem is echoing chars back to the user so
they can see what they typed, and providing some primitive sort of
editing so they can back up when typing strings.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top