How to Read a Single Char from the Console in Java (As the User Types It)

How to read a single char from the console in Java (as the user types it)?

What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.

Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:

If your program must be console based,
you have to switch your terminal out
of line mode into character mode, and
remember to restore it before your
program quits. There is no portable
way to do this across operating
systems.

One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.

Reading a single char in Java

You can either scan an entire line:

Scanner s = new Scanner(System.in);
String str = s.nextLine();

Or you can read a single char, given you know what encoding you're dealing with:

char c = (char) System.in.read();

Reading single character from console in java

Using:

int byte = system.in.read();
char singleChar = (char)byte;

should read a single byte from the console.

Take a char input from the Scanner

You could take the first character from Scanner.next:

char c = reader.next().charAt(0);

To consume exactly one character you could use:

char c = reader.findInLine(".").charAt(0);

To consume strictly one character you could use:

char c = reader.next(".").charAt(0);

How to get control characters from a console input string

You can test for a real control character using the Character::isISOControl methods (javadoc).

However, as noted in the comments, up-arrow and down-arrow are keystrokes rather than characters. What they actually produce in the input stream are platform dependent. For example, if you are using an ANSI-compliant terminal or terminal emulator, an up-arrow will be mapped to the sequence ESC [ A. If you simply filter out the ISO control characters, you will remove the ESC only.

I don't think there is a reliable platform independent way to filter out the junk that results from a user mistakenly typing arrow keys. For a platform specific solution, you need to understand what specific sequences are produced by the user's input device. Then you detect and remove the sequences.



Related Topics



Leave a reply



Submit