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

后端 未结 5 1955
深忆病人
深忆病人 2020-11-21 05:49

Is there an easy way to read a single char from the console as the user is typing it in Java? Is it possible? I\'ve tried with these methods but they all wait for the user t

5条回答
  •  渐次进展
    2020-11-21 06:19

    I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.

    • On Windows it uses _kbhit() and _getwch() from msvcrt.dll.
    • On Unix it uses tcsetattr() to switch the console to non-canonical mode, System.in.available() to check whether data is available and System.in.read() to read bytes from the console. A CharsetDecoder is used to convert bytes to characters.

    It supports non-blocking input and mixing raw mode and normal line mode input.

提交回复
热议问题