This entry deals with how to handle input character by character when writing a program that runs console I / O in Java.
In Java, there are Streams that handle standard I / O, which allows you to "read" input character by character, but not directly handle keystroke events.
For this reason, for example, when creating a "calculator" program, if you press "+", something will be done immediately, which cannot be achieved with the standard library alone.
JLine3 is a library that you can use when developing CUI applications. It is also used by some well-known OSS.
JLine3 also supports platform-specific terminal control in Windows environments. Since a platform-native library is required here, a method using JNA or JANSI is provided. This entry uses JNA.
If you use the code below, you can input each character from the terminal and immediately display it on the standard output.
package com.hrkt.commandlinecalculator;
import lombok.extern.slf4j.Slf4j;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
@Slf4j
public class CommandlineInterface {
public void run(String... args) {
log.info("hello");
try(Terminal terminal = TerminalBuilder.terminal()) {
int ch = 0;
while ((ch = terminal.reader().read()) != 0x09){
// TAB(0x09)Exit with
char c = (char)ch;
System.out.println(String.format("%d, %c", ch, ch));
}
} catch(IOException e) {
log.error(e.getMessage(), e);
}
}
}
The movement is as shown in the figure below.
In this entry, I showed you how to handle keystrokes from the console in Java. I see articles that use JLine2, but it has been developed and it is recommended to use JLine3.
A working sample can be found below.
https://github.com/hrkt/commandline-calculator/releases/tag/0.0.2
Recommended Posts